C#超时后中止异步HttpWebRequest

标签 c# httpwebrequest cancellation-token

我在这里找到了https://stackoverflow.com/a/19215782/4332018CancellationTokenasync 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 并且可以在预设时间后取消?

最佳答案

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

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

关于C#超时后中止异步HttpWebRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52390383/

相关文章:

c# - 如何从重定向的网址下载文件?

http - 有没有办法允许 Google App Engine 通过 DELETE 请求发送正文或有效负载?

asp.net - IsPostBack、IsAsync 和 IsCallback 之间有什么区别?

c# - 如何在 MVP 中设置控件状态

c# - C#中如何继承System.Data.SQLite

c# - 使用 "return"终止或退出 C# 异步方法

c# - parallel.foreach - loopState.Stop() 与 Cancellation

task-parallel-library - 将CancellationToken传递给Task.Factory.StartNew()的目的是什么

c# - 如何将命令中的文本框文本作为参数传递 WPF

c# - 重构参数和单元测试