Background Tasks

Costs

var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
if(cost == BackgroundWorkCost.High)
{
  return;
}

Handling cancelation

public async void Run(IBackgroundTaskInstance taskInstance)
{
  var cancel = new System.Threading.CancellationTokenSource();
  taskInstance.Canceled += (s, e) =>
  {
    cancel.Cancel();
    cancel.Dispose();
  }

  var deferral = taskInstance.GetDeferral();
  
  try
  {
    var host = new Windows.Networking.HostName("server.com");
    var socket = new Windows.Networking.Sockets.StreamSocket();
    await socket.ConnectAsync(host, "http").AsTask(cancel.Token);
  }
  finally
  {
    deferral.Complete();
  }
}

Running in a deferral

var deferral = taskInstance.GetDeferral();

try
{
  await Task.Run(async() =>
  {
    for (int i = 0; i < 10; i++)
    {
      taskInstance.Progress = (uint)i * 10;
      await Task.Delay(2000);
    }
   });
}
catch {}
finally
{
  deferral.Complete();
}

Request Background Permission

var allowed = await BackgroundExecutionManager.RequestAccessAsync();

switch(allowed)
{
  // allowed
  case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:
  break;
  
  case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:
  break;

  // denied
  case BackgroundAccessStatus.Denied:
  break;

  // canceled
  case BackgroundAccessStatus.Unspecified:
  break;
}

Build and register task

var task = new BackgroundTaskBuilder
{
  Name = nameof(MyBackgroundTask),
  CancelOnConditionLoss = false,
  TaskEntryPoint = typeof(MyBackgroundTask).ToString()
};

task.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));   // Trigger
task.AddCondition(new SystemCondition(SystemConditionType.UserPresent));  / / Condition
task.Register();

 

Background Triggers

  • SystemTrigger (Windows 8.1)
  • TimeTrigger (Windows 8.1)
  • MaintenanceTrigger (Windows 8.1)
    • Requires A/C Power, If unplugged, it will be canceled
    • It is a long-running task
    • Not guaranteed to run, can be cancelled
    • Minimum Intervall is 15 Minutes
    • One shot (repeating)
  • DeviceUseTrigger (Windows 8.1)
    • It is a long-running task
  • DeviceServicingTrigger (Windows 8.1)
  • PushNotificationTriger (Windows 8.1)
  • CachedFileUpdaterTrigger (Windows Phone 8.1)
  • DeviceConnectionChangeTrigger (Windows Phone 8.1)
  • GattCharacteristicNotificationTrigger (Windows Phone 8.1)
  • RfcommConnectionTrigger (Windows Phone 8.1)
  • LocationTrigger (Windows Phone 8.1)
  • AppointmentStoreNotificationTrigger (Windows 10)
  • ContactStoreNotificationTrigger (Windows 10)
  • EmailStoreNotificationTrigger (Windows 10)
  • BluetoothLEAdvertisementWatcherTrigger (Windows 10)
  • BluetoothLEAdvertisementPublisherTrigger (Windows 10)
  • DeviceWatcherTrigger (Windows 10)
  • ActivitySensorTrigger (Windows 10)
  • SensorDataThresholdTrigger (Windows 10)
  • ToastNotificationHistoryChangedTrigger (Windows 10)
  • ToastNotificationActionTrigger (Windows 10)
  • ApplicationTrigger (Windows 10)
    • It is a long-running task
  • MediaProcessingTrigger (Windows 10)
  • SocketActivityTrigger (Windows 10)

Trigger Interval

  • Minimum Timespan is 15 Minutes

Add a Trigger

var triggerType = SystemTriggerType.TimeZoneChange;
var trigger = new SystemTrigger(triggerType, oneShot: false);
var builder = new BackgroundTaskBuilder();
builder.SetTrigger(trigger);

Conditions

  • User Present
  • User Not Present
  • Internet Available
  • Internet Not Available
  • Session Connected (User is logged in)
  • Session Disconnected (User is not logged in)
  • Free Network Available (non-metered Network ia available)
  • Work Cost Not High

Register a Background Task with a Condition

var conditionType = SystemConditionType.InternetAvailable;
var condition = new SystemCondition(conditionType);
var builder = new BackgroundTaskBuilder();
builder.AddCondition(condition);

Background Recources

Task constraints

  • CPU time quota = NO
  • CPU guarantee = YES (10%)
  • Wall clock quoata = YES
    • 25s for Default Tasks
    • XXs for Long-running Tasks
    • After cancellation event + 5s
  • Memory quota = YES (min. 16 MB)
  • Network quota = YES (depends on device)
  • Can be cancelled at any time (5s for Shutdown)
  • Default Tasks
    • Hosted in seperate Process „backgroundtaskhost.exe“
    • Seperate memory cap
  • In-process Tasks
    • Simplified communication
    • Shares memory caps
    • Foreground app starts in app.exe
    • Background task starts in app.exe
    • Background will be terminated if Forground Task (App) stops

Configure In-Proc Background Task

Manifest

<Extension 
  Category="windows.backgroundTasks" 
  EntryPoint="BackgroundTasks.TimerTask"
  Executable="MyApp.exe"
>

User-invoked constraints

  • Quiet hours
  • Battery Saver

Debugging Background Tasks

Application log

Application & Services Logs > Microsoft > BackgroundTaskInfrastructure

PowerShell cmdlets

  • Test with global pool disabled
    Set-AppBackgroundTaskResourcePolic -Mode Conservative
  • See resource usage
    Get-AppBackgroundTask -ResourceUsage

Use in Visual Studio: „Debug My App But Do Not Launch“