0
我正在使用xamarin表单PCL + iOS。我想在进入后台时取消任务。当应用程序进入前台时,从头开始。应用程序进入后台时的任务取消
这就是我到目前为止所尝试过的。我不确定我的方式取消了任何任务,或者在这里发生了什么?
async void getData()
{
bool isSuccess = await getSomeData();
if(isSuccess)
await getSomeMoreData();
}
CancellationTokenSource cts;
async Task<bool> getSomeData()
{
cts = new CancellationTokenSource();
AppEntersBackgorund += (sender,args) => { cts. cancel();});
CancellationToken token = new CancellationToken();
token = cts.token;
await Task.Run(() => {
token.ThrowIfCancellationRequested();
isSuccess = ParserData(token); // parsedata also checks periodically if task is cancelled
},token); //what happens here when cancel called?
return isSuccess;
}
async void getSomeMoreData()
{
if(!cts.IsCancellationRequested)
cts = new CancellationTokenSource();
AppEntersBackgorund += (sender,args) => { cts. cancel();});
CancellationToken token = new CancellationToken();
token = cts.token;
await Task.Run(() =>
{
token.ThrowIfCancellationRequested();
ParseSomeMoreData(token);
},token);
}
当应用程序进入foregorund,我再次调用getData()方法,这样我从头再来。
发生什么事是,任务没有被取消,而是getSomeMoreData被调用两次(或应用程序从背景到前景的次数)。
有人可以解释我怎么能做到这一点?这里发生了什么?