扩展执行无法正常工作?

Rom*_*asz 18 c# win-universal-app windows-10-mobile

我无法ExtendedExecution正常工作.问题是Revoked在执行完成之前不会触发事件.如果我们采样:

private async void OnSuspending(object sender, SuspendingEventArgs e)
{
    Debug.WriteLine("Suspending in app");
    var deferral = e.SuspendingOperation.GetDeferral();
    using (var session = new ExtendedExecutionSession())
    {
        session.Reason = ExtendedExecutionReason.SavingData;
        session.Description = "Upload Data";
        session.Revoked += (s, a) => { Debug.WriteLine($"Extended execution revoked because of {a.Reason}"); };
        var result = await session.RequestExtensionAsync();
        if (result == ExtendedExecutionResult.Denied) Debug.WriteLine("Extended execution failed");
        else
        {
            Debug.WriteLine("Executing");
            await Task.Run(() => { Task.Delay(9000).Wait(); Debug.WriteLine("Finished the task"); });
            Debug.WriteLine("Executing finished");
        }
        Debug.WriteLine("Suspending after execution");
    }
    deferral.Complete();
}
Run Code Online (Sandbox Code Playgroud)

文档声明Revoked应该在恢复应用程序时触发事件,但如果您尝试附加调试器的代码,那么您将看到调试输出看起来没问题,但您必须等待9000毫秒才能显示它.这意味着代码将暂停,直到会话结束.

最大的问题是,如果你在没有连接调试器的情况下启动它,启动应用程序,暂停然后恢复,你会看到黑屏几秒钟,然后操作系统将终止你的应用程序.

我错过了什么吗?有没有人让它正常工作?

Jai*_*ero 1

使用awaitandTask会导致您继续执行的任务保留在主线程上,从而使您必须等待黑屏。请记住,该await行为是将执行安排到 ThreadPool 中Dispatcher,而不是开始新线程,也不将其执行安排到 ThreadPool 中。因此,在Delay()结束之前无法处理更多 UI 消息。

只需在新线程上执行耗时的操作,但确保保持会话打开直到结束。

查看此https://msdn.microsoft.com/en-us/magazine/jj991977.aspx以深入了解如何安排执行