gpt4 book ai didi

c# - 应用程序停用时如何处理后台线程

转载 作者:行者123 更新时间:2023-11-30 20:51:15 24 4
gpt4 key购买 nike

我正在使用后台线程对网络服务进行异步调用并返回结果。当后台线程正在运行并且我的应用程序被停用时,假设用户按下了主页按钮,我该如何处理?

private async void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
//What should I do here?
}

我从下面的博客中了解到http://www.wintellect.com/blogs/jgarland/proceed-with-caution---windows-phone-8-app-lifecycle-events-vs-async-methods我不能等待,直到后台线程在停用方法中完成。它还建议使用同步调用。如果我必须在停用事件中取消我的后台线程,我如何找到目前正在运行的后台线程?在每个页面中在调用web服务的地方,使用了后台线程。有没有办法在应用程序再次激活后恢复后台线程?

最佳答案

你是对的,当你的应用程序被停用时,所有进程都会停止 - MSDN source :

When the user navigates forward, away from an app, after the Deactivated event is raised, the operating system will attempt to put the app into a dormant state. In this state, all of the application’s threads are stopped and no processing takes place, but the application remains intact in memory.

在您的停用事件中,您应该向所有后台线程调用取消请求。如果您使用 aync-await然后你可以用 CancellationTokenSource 装备这些方法.以下是更多相关信息:Enabling Progress and Cancellation in Async , Cancel an Async Task or a List of Tasks , 你可以找到很多关于 Stephen Cleary blog 的信息.

至于知道哪个任务正在运行的问题,我认为您可以使用此 CancellationTokenSource 来检查它 - 如果它不为空,则表示您的后台线程正在运行。

至于重新激活您的方法 - 一切都取决于您的代码和该方法执行的操作。如果您正在下载一组文件,那么您可以记住下载了哪些文件,并在激活调用方法后下载其余文件。如果您执行一些计算,那么您可以记住该方法停止的地方并尝试恢复进一步的计算。认为有时很难。你必须记住你有 limited time to 10 seconds :

You should not wait until the Deactivated event occurs to store this data. Remember that all application lifecycle events enforce a limit of 10 seconds for an application to complete any tasks.


关于其他可能性:

如果你想在后台进程中执行一些操作 - 那么你可以使用 Background agentsBackground transfers如果你想下载一个文件。还有背景音频,但我想您不会问这个问题。

如果您希望您的应用程序在锁屏时保持在前台,那么您可以 Deactivate Idle Detection .

关于c# - 应用程序停用时如何处理后台线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21871048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com