【问题标题】:c# abort async HttpWebRequest after timeoutc#超时后中止异步HttpWebRequest
【发布时间】:2019-06-29 17:50:03
【问题描述】:

我在这里找到了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 并在预设时间后取消?

【问题讨论】:

  • 为什么不使用请求的 Timeout 属性?
  • @MojtabaTajik 我使用代理并且遇到使用超时问题。

标签: c# httpwebrequest cancellation-token


【解决方案1】:

创建令牌源时,设置取消。然后传入令牌。它应该超时。

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);

【讨论】:

    【解决方案2】:

    希望对你有帮助

     _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();
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多