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

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

Patricia Arquette
Patricia ArquetteOriginal
2025-01-27 22:21:09232browse

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

Elegant processing asynchronous task timeout: cancel task.wait ()

In this code, the method is instantaneous in a programmatic method of a web browser, navigating to a URL, and returning the final URL after the document is loaded. In order to stop the task when the document is loaded for more than 5 seconds and

return NULL, you can use the timeout task method. The following is the code after modified:

GetFinalUrl GetFinalUrl() In this modified code, the

constructor creates a
<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);
    // 创建一个超时取消令牌源
    using (var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
    {
        var task = MessageLoopWorker.Run(DoWorkAsync, trackingUrl, timeoutCts.Token);
        try
        {
            // 在超时时间内等待任务完成
            task.Wait(timeoutCts.Token);
            if (!String.IsNullOrEmpty(task.Result?.ToString()))
            {
                return new Uri(task.Result.ToString());
            }
        }
        catch (OperationCanceledException)
        {
            // 任务超时,返回null
            return null;
        }
    }
    throw new Exception("解析失败");
}</code>
(TimeoutCTs) with a timeout of 5 seconds. Then use the method to wait for the task to be completed within the specified timeout of

. If the task is not completed during the timeout, the CancellationTokenSource(TimeSpan) abnormalities are thrown, and the CancellationTokenSource method returns NULL. Pay attention to to add air checks to avoid potential NullReferenceException. Wait(CancellationToken) CancellationToken In this way, we effectively avoid long -term obstruction and handle the potential timeout elegantly. OperationCanceledException

The above is the detailed content of How to Cancel a Task.Wait() After a Timeout?. 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