C# Windows 10物联网生命周期(或:如何终止后台应用程序)
为了在具有Windows 10 IOT核心的无头Raspberry Pi 2上使用UWP应用程序,我们可以使用后台应用程序模板,该模板基本上创建了一个新的UWP应用程序,其中只包含启动时执行的后台任务:C# Windows 10物联网生命周期(或:如何终止后台应用程序),c#,.net,win-universal-app,C#,.net,Win Universal App,为了在具有Windows 10 IOT核心的无头Raspberry Pi 2上使用UWP应用程序,我们可以使用后台应用程序模板,该模板基本上创建了一个新的UWP应用程序,其中只包含启动时执行的后台任务: <Extensions> <Extension Category="windows.backgroundTasks" EntryPoint="BackgroundApplication1.StartupTask"> <BackgroundTasks>
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundApplication1.StartupTask">
<BackgroundTasks>
<iot:Task Type="startup" />
</BackgroundTasks>
</Extension>
</Extensions>
这样,应用程序将保持运行,并且操作系统不会在IOT世界中任何超时后终止应用程序
到目前为止,一切都很好
但是:我希望能够在设备关闭时正确关闭后台应用程序(或者要求应用程序“轻轻”关闭)
在“普通”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();
}
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();
}