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

笑着哭i 提交于 2019-12-12 08:28:41

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/30429461/windows-10-iot-lifecycle-or-how-to-property-terminate-a-background-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!