首页 > 解决方案 > c#超时后中止异步HttpWebRequest

问题描述

我在这里https://stackoverflow.com/a/19215782/4332018找到了一个很好的解决CancellationToken方案async 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()and CancelAfter(Int32),但不明白如何修改上面的例子来使用CancellationTokenSource,因为它没有Register方法。

我怎样才能async HttpWebRequest在预设时间后取消的可能性?

标签: c#httpwebrequestcancellation-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);

推荐阅读