uwp Register background task with trigger


Example

The background task are a great way to perform some work while your application is not running. Before being able to use then , you will have to register them.

Here is a sample of a background task class including the registration with a trigger and a condition and the Run implementation

public sealed class Agent : IBackgroundTask
{    
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        // run the background task code
    }
    
    // call it when your application will start.
    // it will register the task if not already done
    private static IBackgroundTaskRegistration Register()
    {
        // get the entry point of the task. I'm reusing this as the task name in order to get an unique name
        var taskEntryPoint   = typeof(Agent).FullName;
        var taskName         = taskEntryPoint;
        
        // if the task is already registered, there is no need to register it again
        var registration            = BackgroundTaskRegistration.AllTasks.Select(x => x.Value).FirstOrDefault(x => x.Name == taskName);
        if(registration != null) return registration;
                        
        // register the task to run every 30 minutes if an internet connection is available
        var taskBuilder             = new BackgroundTaskBuilder();
        taskBuilder.Name            = taskName;
        taskBuilder.TaskEntryPoint  = taskEntryPoint;
        taskBuilder.SetTrigger(new TimeTrigger(30, false));
        taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
        
        return taskBuilder.Register();
    }
}