Home >Backend Development >C++ >How to Cancel a Task.Wait() After a Timeout in C#?

How to Cancel a Task.Wait() After a Timeout in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-27 22:16:13638browse

How to Cancel a Task.Wait() After a Timeout in C#?

Timeout cancellation of Task.Wait() method in C#

In this code, MessageLoopWorker.Run is started on a new thread with a message pump, and the DoWorkAsync task is executed on this thread. Then wait for the task on the main thread, blocking the main thread until the task is completed.

In order to cancel the task after timeout, you can use the CancellationToken class. CancellationToken class allows you to propagate cancellation requests from one thread to another.

Here's how to modify your code to cancel the task after timeout:

<code class="language-csharp">private Uri GetFinalUrl(PortalMerchant portalMerchant)
{
    SetBrowserFeatureControl();
    Uri finalUri = null;
    if (string.IsNullOrEmpty(portalMerchant.Url))
    {
        return null;
    }
    Uri trackingUrl = new Uri(portalMerchant.Url);

    // 创建一个 CancellationTokenSource。
    using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())
    {
        // 设置 5 秒的超时时间。
        using (Timer timer = new Timer(state => cancellationTokenSource.Cancel(), null, 5000, Timeout.Infinite))
        {
            try
            {
                // 使用 CancellationToken 启动任务。
                var task = MessageLoopWorker.Run(DoWorkAsync, cancellationTokenSource.Token, trackingUrl);

                // 等待任务完成。
                task.Wait(cancellationTokenSource.Token);

                // 如果任务成功完成,获取结果。
                if (!string.IsNullOrEmpty(task.Result?.ToString()))
                {
                    return new Uri(task.Result.ToString());
                }
            }
            catch (OperationCanceledException)
            {
                // 任务被取消。
            }
            catch (AggregateException ex)
            {
                // 处理任务中的其他异常
                foreach (var innerException in ex.InnerExceptions)
                {
                    // Log or handle inner exception appropriately
                    Console.WriteLine($"Inner Exception: {innerException.Message}");
                }
            }
        }
    }

    // 如果任务被取消或失败,则返回 null。
    return null;
}</code>

In this code, we create a CancellationTokenSource and pass it CancellationToken to the MessageLoopWorker.Run method. We also set a timer to cancel the token after 5 seconds. If the task completes successfully before timing out, we will get the result. If the task is cancelled, we capture OperationCanceledException. Finally, we release the using and CancellationTokenSource resources using the Timer statement to ensure the resources are handled correctly. Additionally, a AggregateException handler has been added to catch and handle other exceptions that may arise in the DoWorkAsync task.

This improved version uses using statements for proper resource management, preventing resource leaks. The addition of AggregateException handling makes the code more robust. Remember to handle the inner exceptions appropriately within the AggregateException catch block, such as logging them or taking other corrective actions.

The above is the detailed content of How to Cancel a Task.Wait() After a Timeout in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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