Home >Backend Development >C++ >How to Cancel a Task.Wait() After a Timeout?
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
<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!