gpt4 book ai didi

c# - 将后台安全任务与 async/await 一起使用时的正确实现

转载 作者:太空宇宙 更新时间:2023-11-03 23:46:00 24 4
gpt4 key购买 nike

如果用户按下主页按钮或正在打开应用程序切换器或正在接听来电,则当前正在运行的任务(网络请求)应该在后台完成。我没有为此使用 NSURLSession,因为我现在不想更改当前的基础类。因此我想利用 background-safe tasks .

我试过这个:

public async Task retrieveCarList(){
backgroundTaskID = UIApplication.SharedApplication.BeginBackgroundTask (() => {
if(backgroundTaskID != 0){
UIApplication.SharedApplication.EndBackgroundTask(backgroundTaskID);
backgroundTaskID = 0;
}
});

List<Car> carList = await manager.GetCarList();
if(carList != null) {
this.list = carList;
} else {
new UIAlertView("Error occurred", "", null, "OK", null).Show();
}

if(backgroundTaskID != 0){
UIApplication.SharedApplication.EndBackgroundTask(backgroundTaskID);
backgroundTaskID = 0;
}
}

这似乎可行,但我必须进行更多测试。

问题:

  1. 我可以在应用程序的任何地方使用 BeginBackgroundTask/EndBackgroundTask 吗?大多数examples仅在 DidEnterBackground ...

  2. 中使用它
  3. 系统如何知道这个后台线程的开始和结束位置?

  4. BeginBackgroundTaskEndBackgroundTask 之间的代码是否执行甚至使用了 UI 相关的东西?

  5. 这是博文 Multitasking in iOS: the MonoTouch way – Part I: Pressing the Home button 之后的正确实现吗?但使用 async/await?

编辑 1:

现在我尝试使用 Console.WriteLine。似乎执行了 await 表达式,但只有在用户再次打开应用程序时才会执行之后的代码。我担心的是 EndBackgroundTask 仅在用户返回应用程序时执行。因此,如果未调用 EndBackgroundTask,应用程序可能会被终止。

另一方面,如果我不使用后台安全任务,则如果按下主页按钮,应用程序将不再在后台执行 Web 请求。所以它有点管用......

如何将所有代码行放入 await 表达式中?那么所有的代码都应该被执行还是?

编辑 2:

await 表达式放在 System.Action 之间会导致应用程序崩溃并且不会显示任何错误。我还尝试在 retrieveCarList() 中使用 BeginBackgroundTask 并在等待的 GetCarList() 中使用 EndBackgroundTask,但是仅当我返回应用程序时才会执行代码。此外,我尝试将我的 await 包装在另一个 Task.Run 中,但这带来了问题,因为我正在访问 UI 相关的东西,而这对于这种结构是不可能的。我的第一次尝试似乎仍然是最好的,但它有上面提到的缺点。如果有人有更好的实现,请发布。

最佳答案

解决方案:

1.) Xamarin docs说我可以在任何地方使用这种模式。 Apple docs 中也说明了这一点.

You can call this method at any point in your app’s execution.

2.) Dimitris Tavlikos states

It is after the BeginBackgroundTask call where your background time starts.

3.) 根据 Developing C# Apps for iPhone and iPad using MonoTouch: iOS Apps Development by Bryan Costanich,UI 线程似乎已暂停.

4.) 我的方法似乎很有效。现在我将我的 Console.WriteLine 放在 EndBackgroundTask 之前,它应该被调用! BeginBackgroundTaskEndBackgroundTask 之间的所有内容都会被执行。只有backgroundTaskID没有清除,其他实现也没有清除。

关于c# - 将后台安全任务与 async/await 一起使用时的正确实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606605/

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