Creating a Background Service for Windows IoT Core

Posted by: john.doe on

Overview

Background services are essential for running long‑running tasks on Windows IoT devices without user interaction. This guide walks you through creating a BackgroundTask using the Windows.ApplicationModel.Background namespace.

Sample Code

C# – BackgroundTask.cs
using System;
using Windows.ApplicationModel.Background;

public sealed class MyBackgroundTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        // Prevent the task from being terminated.
        var deferral = taskInstance.GetDeferral();

        // Your background code here.
        System.Diagnostics.Debug.WriteLine("Background task is running");

        // Complete the deferral when done.
        deferral.Complete();
    }
}

Registering the Task

C# – App.xaml.cs
using Windows.ApplicationModel.Background;

public sealed partial class App : Application
{
    protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        RegisterBackgroundTask();
        // Other launch code...
    }

    private void RegisterBackgroundTask()
    {
        var taskBuilder = new BackgroundTaskBuilder
        {
            Name = "MyBackgroundTask",
            TaskEntryPoint = "MyNamespace.MyBackgroundTask"
        };

        // Example: trigger every 15 minutes
        taskBuilder.SetTrigger(new TimeTrigger(15, false));
        var task = taskBuilder.Register();
    }
}

Best Practices

Comments