c# - 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
在预设时间后取消的可能性?
解决方案
创建令牌源时,设置取消。然后传入令牌。它应该超时。
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);
推荐阅读
- java - 用户是否可以授予应用程序权限,以便应用程序可以在需要时让设备可被发现?
- maven - Maven类污染?
- android - 使应用程序在手机屏幕上工作并在应用程序内编辑屏幕截图
- php - 在laravel中以自定义格式返回验证器响应?
- android - 为什么 Firebase 和 Google Analytics 指标不匹配?
- python - 在pygame中添加按钮并说颜色“绿色”是未定义的变量
- google-chrome - 当扩展程序在单独的窗口中启动时,从 Chrome 扩展程序向内容脚本发送消息
- deep-learning - 如何使用 pytorch 从 Resnet 获取概率?
- kotlin - Kotlin 中相同的属性名称和主构造函数参数名称
- amazon-web-services - CloudFormation - 在禁用状态下创建 SNS 订阅