提问人:MainakChoudhury 提问时间:11/17/2023 更新时间:11/17/2023 访问量:30
Xamarin Forms:iOS 中的后台任务限制
Xamarin Forms: Background Task Limitations in iOS
问:
我想在应用程序处于后台时下载下载数据并将其存储在我的 SQL DB 中。
当应用位于前台时,此过程通常需要 45-50 秒。 API 返回 json 大约需要 7-8 秒,然后大约需要 30-40 秒来解析数据并插入到各种表中。
我正在使用 NSURLSession 进行 API 调用,但是在调用 API 并收到所有 JSON 响应后,如果我将 APP 发送到后台,数据库中的插入过程会在 30 秒后中途停止......并在应用返回前台时自行恢复。
这种后台执行的时间限制是什么?
public class iOSLongTaskRunningClass
{
nint _taskId;
CancellationTokenSource cts;
public async Task Start()
{
cts = new CancellationTokenSource();
_taskId = UIApplication.SharedApplication.BeginBackgroundTask("LongRunningTask", OnExpiration);
try
{
var counter = new TaskCounter();
await counter.RunCounter(cts.Token);
}
catch(OperationCanceledException)
{
}
finally
{
if(cts.IsCancellationRequested)
{
Device.BeginInvokeOnMainThread(() => {
MessagingCenter.Send<object>(this, "StopTask");
});
}
}
UIApplication.SharedApplication.EndBackgroundTask(_taskId);
}
void OnExpiration()
{
Console.WriteLine("Background STOPPED "+ DateTime.Now.TimeOfDay.ToString());
Console.WriteLine("Background time remaining: " + UIApplication.SharedApplication.BackgroundTimeRemaining);
cts.Cancel();
}
public void Stop()
{
cts.Cancel();
}
}
}
在 APPDELEGATE 中:
[Export("applicationDidEnterBackground:")]
public override void DidEnterBackground(UIApplication application)
{
Console.WriteLine("Background ENtered " + DateTime.Now.TimeOfDay.ToString());
}
}
输出:
答: 暂无答案
评论