Search code examples
c#uwpbackground-task

Use in-process background tasks with SDK version 10586


I want to extend my current UWP app by a background task. The in-process model perfectly fits my needs as I don't need to change much from the application to use background task. However, there's one problem. The minimum SDK version is set to 10586 at the moment but the in-process background tasks are only available for SDK version 14393 and higher.

Normally I'd use a 'normal' if-clause to check if the feature is supported using the Windows.Foundation.Metadata.ApiInformation namespace. Unfortunately, as I am overriding the OnBackgroundActivated method, this is not possible. I honestly don't want to drop 10586 support, at least not at this moment.

Is there an easy way to register in-process background tasks while keeping the support for 10586?

EDIT: As I was asked in a (now deleted) comment: No, I didn't execute the app on build 10586 yet, as my internet connection is damn slow. I'm asking, because Visual Studio won't build the app when I set the target version to 10586.


Solution

  • The OnBackgroundActivated method you're overriding is not the problem here, as on 10586 it simply never gets called. To create the project for both versions in the Properties of your project set the target versions like this: Target versions in Applications tab

    What will cause some trouble is calling BackgroundExecutionManager.RequestAccessAsync();. This method call used on 10586 expects that you have a BackgroundTask definied in your Package.appxmanifest that you don't have to in your case, because it is not required according to the documentation. So in order to reuse the code change your method registering your in-process BackgroundTask to something like this:

    public static async Task<bool> RegisterInProcessBackgroundTask(string taskName, uint time = 30) {
        try {
            await BackgroundExecutionManager.RequestAccessAsync();
    
            BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
            taskBuilder.Name = taskName;
            taskBuilder.SetTrigger(new TimeTrigger(time, false));
            BackgroundTaskRegistration registration = taskBuilder.Register();
    
            return true;
        } catch {
            return false;
        }
    }
    

    This will work on 14393+ and return true because the task was registered successfully and return false after catching the Exception because that type of task is not supported on 10586.