Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows 10 IOT Lifecycle (or: how to property terminate a background application)

In order to use a UWP application on a headless Raspberry Pi 2 with Windows 10 IOT Core we can use the background application template which basically creates a new UWP app with just a background task that is executed on startup:

<Extensions>
  <Extension Category="windows.backgroundTasks" EntryPoint="BackgroundApplication1.StartupTask">
    <BackgroundTasks>
      <iot:Task Type="startup" />
    </BackgroundTasks>
  </Extension>
</Extensions>

In order to keep an application running, we can use the following startup code:

public void Run( IBackgroundTaskInstance taskInstance )
{
  BackgroundTaskDeferral Deferral = taskInstance.GetDeferral();

  //Execute arbitrary code here.
}

This way the application keeps running and the OS won't kill the app after any timeout in the IOT universe.

So far, so great.

However: I want to be able to properly close the background application when the device shuts down (or the application is asked to 'gently' close.

In a 'normal' UWP application you can subscribe to the OnSuspending event.
How can I get a notification about an imminent shutdown / close in this background scenario?

Help is greatly appreciated.
Thanks in advance!
-Simon

like image 207
Simon Mattes Avatar asked May 24 '15 23:05

Simon Mattes


1 Answers

You need to handle the canceled event. The background task will be canceled if the device is shutdown properly. Windows will also cancel tasks if they unregistered.

    BackgroundTaskDeferral _defferal;
    public void Run(IBackgroundTaskInstance taskInstance)
    {
         _defferal = taskInstance.GetDeferral();
        taskInstance.Canceled += TaskInstance_Canceled;
    }

    private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
    {
        //a few reasons that you may be interested in.
        switch (reason)
        {
            case BackgroundTaskCancellationReason.Abort:
                //app unregistered background task (amoung other reasons).
                break;
            case BackgroundTaskCancellationReason.Terminating:
                //system shutdown
                break;
            case BackgroundTaskCancellationReason.ConditionLoss:
                break;
            case BackgroundTaskCancellationReason.SystemPolicy:
                break;
        }
        _defferal.Complete();
    }

Cancellation Reasons

Canceled Event

like image 192
Tim Avatar answered Nov 09 '22 23:11

Tim