【问题标题】:Windows 10 IOT Lifecycle (or: how to property terminate a background application)Windows 10 IOT 生命周期(或:如何终止后台应用程序)
【发布时间】:2015-05-24 23:34:56
【问题描述】:

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

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

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

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

  //Execute arbitrary code here.
}

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

到目前为止,非常棒。

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

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

非常感谢您的帮助。
提前致谢!
-西蒙

【问题讨论】:

    标签: c# .net win-universal-app


    【解决方案1】:

    您需要处理取消的事件。如果设备正常关机,后台任务将被取消。如果任务未注册,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();
        }
    

    Cancellation Reasons

    Canceled Event

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多