Background Tasks

Background tasks allow your Universal Windows Platform (UWP) app to perform operations on a schedule or in response to system events without requiring the user to have your app in the foreground. This is crucial for maintaining responsiveness, providing timely updates, and conserving battery life.

Overview

Background tasks can be triggered by various events, such as system maintenance, user activity, or network changes. They run in a separate process from your main application, meaning they can execute even when your app is closed.

Key Concepts

Common Background Task Scenarios

API Reference

Classes

Class Description
BackgroundTaskRegistration Represents a registered background task.
BackgroundTaskBuilder Used to create and configure background tasks before registration.
IBackgroundTask The interface that your background task class must implement.
BackgroundTrigger The base class for all background task triggers.

Triggers

Trigger Type Description
MaintenanceTrigger Fires during system maintenance, which occurs when the device is idle.
TimeTrigger Fires after a specified period of time has elapsed.
NetworkConnectivityTrigger Fires when the network connectivity changes or meets certain criteria.
PushNotificationTrigger Fires when a push notification is received.
SystemCondition Represents conditions like device not being in battery saver mode.

Example: Registering a Maintenance Task

This example demonstrates how to register a background task that runs during system maintenance.


using Windows.ApplicationModel.Background;

// ... inside your app's main activation point or a relevant method

public async void RegisterBackgroundTask()
{
    var requestStatus = await BackgroundExecutionManager.RequestAccessAsync();
    if (requestStatus == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity ||
        requestStatus == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity)
    {
        BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
        taskBuilder.Name = "MyMaintenanceTask";
        taskBuilder.TaskEntryPoint = "MyBackgroundTasks.MaintenanceTask"; // Namespace.ClassName

        MaintenanceTrigger maintenanceTrigger = new MaintenanceTrigger(
            15, // Run at least every 15 minutes
            false // Don't block a currently running background task
        );
        taskBuilder.SetTrigger(maintenanceTrigger);

        // Optional: Add conditions
        var condition = new SystemCondition(SystemConditionType.UserPresent);
        taskBuilder.AddCondition(condition);

        try
        {
            BackgroundTaskRegistration registration = taskBuilder.Register();
            registration.Completed += Registration_Completed;
            System.Diagnostics.Debug.WriteLine("Background task registered successfully.");
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error registering background task: {ex.Message}");
        }
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("Background task registration denied.");
    }
}

private void Registration_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
    // Handle task completion (e.g., check for errors)
    System.Diagnostics.Debug.WriteLine($"Task '{sender.Name}' completed.");
}
            

Example: Implementing an IBackgroundTask

This is the entry point class for the background task registered above.


using Windows.ApplicationModel.Background;
using System;
using System.Threading.Tasks;

namespace MyBackgroundTasks
{
    public sealed class MaintenanceTask : IBackgroundTask
    {
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Get deferral to keep the task running
            var deferral = taskInstance.GetDeferral();

            try
            {
                System.Diagnostics.Debug.WriteLine("Maintenance task started.");

                // Perform your background work here
                await Task.Delay(5000); // Simulate work

                System.Diagnostics.Debug.WriteLine("Background work completed.");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Maintenance task error: {ex.Message}");
            }
            finally
            {
                // Release deferral when done
                deferral.Complete();
                System.Diagnostics.Debug.WriteLine("Maintenance task finished.");
            }
        }
    }
}
            
Important: Your background task entry point class (e.g., MaintenanceTask) must be declared as sealed and contain a public Run method that takes an IBackgroundTaskInstance parameter.

Keywords:

Background Tasks UWP Windows API Task Registration Triggers MaintenanceTrigger IBackgroundTask Asynchronous System Events