【发布时间】:2016-09-26 08:54:41
【问题描述】:
我正在研究 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);
}
当应用程序进入前台时,我再次调用 getData() 方法,以便重新开始。
发生的情况是,Task 没有被取消,而是 getSomeMoreData 被调用了两次(或应用程序从后台转到前台的次数)。
有人可以解释我如何实现这一目标吗?这里发生了什么?
【问题讨论】:
标签: c# ios iphone xamarin.ios xamarin.forms