Effectively cancels the task if await
is used
When working with a WinRT task, you may try to terminate the task using the CancelNotification
method. However, this code may cause unexpected results because the task will actually continue to complete even if you try to cancel. In order to overcome this limitation and actually stop the task when cancelled, follow these steps:
Integrate cancellation functionality into your method by passing the CancellationToken
object. Ensure that every method that can be terminated periodically validates this token.
The modified code snippet effectively cancels the task as expected:
<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); try { await task; } catch (OperationCanceledException) { // 处理取消 } } private int slowFunc(int a, int b, CancellationToken cancellationToken) { string someString = string.Empty; for (int i = 0; i < 1000000; i++) { someString += i.ToString(); cancellationToken.ThrowIfCancellationRequested(); // 定期检查取消请求 } return a + b; }</code>
By using the await
block within the try/catch
action, you can handle the OperationCanceledException
and take appropriate actions to mitigate the effects of task cancellation.
The above is the detailed content of How to Properly Cancel an `await`-ing WinRT Task?. For more information, please follow other related articles on the PHP Chinese website!