Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

c# - Extended execution not working properly?

I'm not able to get ExtendedExecution to work properly. The problem is that the Revoked event is not being fired until the execution is finished. If we take a sample:

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

The documentation states that Revoked event should be fired upon resuming the app, but if you try the code with debugger attached, then you will see that debug output seems to look ok, but you have to wait 9000 ms for it to show up. This means that the code is suspended until the session finishes.

The biggest problem is that if you fire this without debugger attached, launch the app, suspend and then resume, you will see a black screen for few seconds and then OS will terminate your app.

Am I missing something? Has anybody got it working correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The usage of the await and Task is causing that your continued Task remains on the main thread making you have to wait with the black screen. Remember that the await behavior is to schedule the execution into the Dispatcher, NOT to begin a new thread, NOR schedule its execution into the ThreadPool. As consequence, No more UI messages can be processed until the Delay() ends.

Just perform your time-consuming operation on a new thread, but ensure to keep the session open until it ends.

Take a look of this https://msdn.microsoft.com/en-us/magazine/jj991977.aspx to get a good insight about how execution is sheduled


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...