Windows Store Background Tasks, as the name suggests, runs in the background when your app is not active. They provide the perfect opportunity for you to send toasts, update live tiles or update the users lock screen. I pulled this particular feature into my app immediately as I saw a couple of use cases for this exact idea. The plan was to check a couple of services and based on the result send a toast to the user, providing a non to subtle reminder that the service I am providing has additional information for immediate consumption. So here goes…

Create your IBackgroundTask

namespace BGTasks
{
    public sealed class ToastNotifier : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var results = await client.MyStuffAsync();
        }
    }
}

DeclarAtions

image

Registration

Registration should occur as soon as the app starts, consider using App.xaml.cs. In this example I register the background task to trigger on the Internet Available trigger.

private void RegisterBackgroundTask()
{
    BackgroundTaskBuilder btb = new BackgroundTaskBuilder();
    btb.Name = "ToastNotifier";
    btb.TaskEntryPoint = "BGTask.ToastNotifier";
    btb.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable, false));

    BackgroundTaskRegistration task = btb.Register();
}

So I completed all the above task and started to call my service and met an immediate road block during testing, apparently calling asynchronous methods from Background Tasks will cause “unexpected behavior” (just stops, no exceptions). In order to get around this we have to update Run method to an async call and also declare which part of the Run method will contain the asynchronous call by using BackgroundTaskDeferral as follows:

public async void Run(IBackgroundTaskInstance taskInstance)
{
	BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
	var results = await client.MyStuffAsync();
	_deferral.Complete();

}

It is that easy!