Home > Backend Development > C++ > How to Properly Cancel Asynchronous Tasks in WinRT?

How to Properly Cancel Asynchronous Tasks in WinRT?

Susan Sarandon
Release: 2025-01-26 12:41:11
Original
220 people have browsed it

How to Properly Cancel Asynchronous Tasks in WinRT?

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>
Copy after login

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:

  • Pass CancellationToken: Pass CancellationToken to every method that supports cancellation.
  • Check CancellationToken periodically: This method must be checked 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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template