我正在检查网址并启动新任务以防止用户界面冻结。
像这样:
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse,null);
重点是......我实现了最长时间(例如10秒)。 如果应用程序在没有响应的情况下达到10秒,则必须中止任务。
答案 0 :(得分:1)
HttpWebRequest
不允许您轻松地将超时应用于异步请求。
我建议您使用更现代的HttpClient
:
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(10);
var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url));
}
如果你被困在HttpWebRequest
地,那么你可以使用一个调用Abort
(未经测试)的计时器:
static async Task<HttpWebResponse> GetResponseWithTimeoutAsync(this HttpWebRequest request, TimeSpan timeout)
{
// Start request and timeout
var delayTask = Task.Delay(timeout);
var requestTask = Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
var completedTask = await Task.WhenAny(delayTask, requestTask);
if (completedTask == delayTask)
{
request.Abort();
throw new TimeoutException();
}
return (HttpWebResponse)(await requestTask);
}