Windows 10 IOT生命周期(或:如何属性终止后台应用程序)

为了在带有Windows 10 IOT Core的无头Raspberry Pi 2上使用UWP应用程序,我们可以使用后台应用程序模板,该模板基本上创建了一个新的UWP应用程序,只有在启动时执行的后台任务:

       

为了使应用程序保持运行,我们可以使用以下启动代码:

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

这样,应用程序将继续运行,并且在IOT Universe中的任何超时后,操作系统都不会终止应用程序。

到目前为止,太棒了。

但是:我希望能够在设备关闭时正确关闭后台应用程序(或者要求应用程序“轻轻地”关闭。

在“普通”UWP应用程序中,您可以订阅OnSuspending事件。
如何在此背景场景中获得有关即将关闭/关闭的通知?

非常感谢帮助。
提前致谢!
-Simon

您需要处理已取消的事件。 如果设备正常关闭,后台任务将被取消。 如果取消注册,Windows也将取消任务。

  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(); } 

取消原因

取消活动