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被調用兩次(或應用程序從背景到前景的次數)。
有人可以解釋我怎麼能做到這一點?這裏發生了什麼?