我正在玩这些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() { }
阅读上取消(这是在.NET 4.0中引入的,是基本不变从那时起)和基于任务的异步模式,它提供了关于如何使用的指导方针CancellationToken与async方法。
CancellationToken
async
总而言之,您将a传递给CancellationToken支持取消的每个方法,并且该方法必须定期检查它。
private async Task TryTask() { CancellationTokenSource source = new CancellationTokenSource(); source.CancelAfter(TimeSpan.FromSeconds(1)); Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token); // (A canceled task will raise an exception when awaited). await task; } private int slowFunc(int a, int b, CancellationToken cancellationToken) { string someString = string.Empty; for (int i = 0; i < 200000; i++) { someString += "a"; if (i % 1000 == 0) cancellationToken.ThrowIfCancellationRequested(); } return a + b; }