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

To use the UWP application for a headless raspberry Pi 2 with Windows IOT Core IOT, we can use a background application template that basically creates a new UWP application with only a background job that runs when it starts:

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

To keep the application running, we can use the following startup code:

 public void Run( IBackgroundTaskInstance taskInstance ) { BackgroundTaskDeferral Deferral = taskInstance.GetDeferral(); //Execute arbitrary code here. } 

Thus, the application continues to work, and the OS will not kill the application 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 turns off (or the application "gently" closes.

In a β€œnormal” UWP application, you can subscribe to the OnSuspending event.
How can I be notified of an imminent close / close in this background scenario?

Help is much appreciated. Thanks in advance! -Simon

+8
c # win-universal-app
source share
1 answer

You need to handle the canceled event. The background task will be canceled if the device is disconnected correctly. Windows also cancels jobs if they are 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(); } 

Reasons for cancellation

Canceled Event

+8
source share

All Articles