我正在玩这些 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()
{
}