我正在玩这些Windows 8 WinRT任务,并且正在尝试使用以下方法取消任务,并且在某种程度上可以正常工作。确实会调用CancelNotification方法,这使您认为任务已被取消,但是在后台任务继续运行,然后在完成后,任务的状态始终为完成且从未取消。取消任务后,是否有办法完全停止任务?
private async void TryTask()
{
CancellationTokenSource source = new CancellationTokenSource();
source.Token.Register(CancelNotification);
source.CancelAfter(TimeSpan.FromSeconds(1));
var task = Task<int>.Factory.StartNew(() => slowFunc(1, 2), source.Token);
await task;
if (task.IsCompleted)
{
MessageDialog md = new MessageDialog(task.Result.ToString());
await md.ShowAsync();
}
else
{
MessageDialog md = new MessageDialog("Uncompleted");
await md.ShowAsync();
}
}
private int slowFunc(int a, int b)
{
string someString = string.Empty;
for (int i = 0; i < 200000; i++)
{
someString += "a";
}
return a + b;
}
private void CancelNotification()
{
}