The correct way to cancel WinRT asynchronous tasks
In Windows 8 WinRT, tasks provide a mechanism to perform asynchronous operations. However, handling task cancellations can be tricky.
Consider the following code:
<code class="language-csharp">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 < 1000000; i++) { someString += i.ToString(); } return a + b; }</code>
Despite the CancelNotification
method being called, the task continues to run in the background and completes. In order to completely stop the task on cancellation, please follow these guidelines:
CancellationToken
to every method that supports cancellation. CancellationToken
periodically. The improved code is as follows:
<code class="language-csharp">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); // (取消的任务在等待时会引发异常)。 await task; } private int slowFunc(int a, int b, CancellationToken cancellationToken) { string someString = string.Empty; for (int i = 0; i < 1000000; i++) { cancellationToken.ThrowIfCancellationRequested(); // 检查取消请求 someString += i.ToString(); } return a + b; }</code>
With these modifications, if a task is canceled during execution, the task will be completely canceled and an exception will be thrown while waiting.
The above is the detailed content of How to Properly Cancel Asynchronous Tasks in WinRT?. For more information, please follow other related articles on the PHP Chinese website!