繁体   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