簡體   English   中英

C#超時后中止異步HttpWebRequest

[英]c# abort async HttpWebRequest after timeout

我在這里https://stackoverflow.com/a/19215782/4332018找到了一個將CancellationTokenasync HttpWebRequest一起使用的不錯的解決方案:

public static class Extensions
{
    public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct)
    {
        using (ct.Register(() => request.Abort(), useSynchronizationContext: false))
        {
            try
            {
                var response = await request.GetResponseAsync();
                return (HttpWebResponse)response;
            }
            catch (WebException ex)
            {
                // WebException is thrown when request.Abort() is called,
                // but there may be many other reasons,
                // propagate the WebException to the caller correctly
                if (ct.IsCancellationRequested)
                {
                    // the WebException will be available as Exception.InnerException
                    throw new OperationCanceledException(ex.Message, ex, ct);
                }

                // cancellation hasn't been requested, rethrow the original WebException
                throw;
            }
        }
    }
}

但是我不明白,如果執行的時間超過預設時間,該如何中止request

我知道CancellationTokenSource()CancelAfter(Int32) ,但是不了解如何修改以上示例以使用CancellationTokenSource ,因為它沒有Register方法。

在預設時間后如何取消async HttpWebRequest

創建令牌源時,請設置取消。 然后傳遞令牌。 它應該超時。

CancellationTokenSource cts = new CancellationTokenSource();
                cts.CancelAfter(1000);

                var ct = cts.Token;

                var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.zzz.com/here");
                var test = Extensions.GetResponseAsync(httpWebRequest, ct);

希望對您有幫助

 _cancelTasks = new CancellationTokenSource();
        string Response = null;
        var task = new Task(() => {

            try
            {
                using (var wb = new WebClient())
                {
                    var data = new NameValueCollection();
                    data["XMLString"] = XMLRequest;
                    var response = wb.UploadValues(ServiceURL, "POST", data);

                }
            }
            catch (Exception ex)
            {
            }
        }, _cancelTasks.Token);
        task.Start();
        if (!task.Wait(GWRequestTimeout * 1000))
        {

            _cancelTasks.Cancel();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM