UWP XamlRenderingBackgroundTask

Before Windows 8.1 there was no way to run UI code in a Background Task. This was possible before, in Windows Phone Silverlight Task Agents but did not work in Windows 8 store applications.
With Windows 8.1 and UWP after that, there’s a simple solution to do this - XamlRenderingBackgroundTask. This is a special kind of background task that can run on the UI thread and so it allows you to, for example, render an image for your live tile.

However, there’s a very small caveat that comes with it and I got burned twice by it wasting a couple of hours debugging.

When you implement a “normal” background task your code looks something like this:

1
2
3
4
5
6
7
public sealed class LiveTileBackgroundTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{

...
}
}

You implement your interface and everything works. However, if you then switch to a XamlRenderingBackgroundTask it stops working. I usually figure it out after a couple of hours of frustration, hopefully this will help you shorten that time. The trick is that the XamlRenderingBackgroundTask already implements the Run() method of the IBackgroundTask and exposes a virtual method OnRun() where you write your code. So while your code won’t work it won’t even throw a compilation error making things perfect to debug.
Here’s the proper code to implement your background task:

1
2
3
4
5
6
7
public sealed class LiveTileBackgroundTask : XamlRenderingBackgroundTask
{
protected override async void OnRun(IBackgroundTaskInstance taskInstance)
{

...
}
}

I am pretty sure it’s documented somewhere but I can never find it quickly when needed. Hope it helps.

Share Comments