【发布时间】:2019-06-29 17:50:03
【问题描述】:
我在这里找到了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()和CancelAfter(Int32),但是不明白如何修改上面的例子使用CancellationTokenSource,因为它没有Register方法。
我如何制作async HttpWebRequest 并在预设时间后取消?
【问题讨论】:
-
为什么不使用请求的 Timeout 属性?
-
@MojtabaTajik 我使用代理并且遇到使用超时问题。
标签: c# httpwebrequest cancellation-token