我正在使用.NETHttpClient
向我的服务器发送请求。我已经设定HttpClient.Timeout
属性为 10 秒,所以我得到了A task was cancelled
每当服务器无法在 10 秒内处理我的请求时,就会出现异常。到这里为止都很好。
However, if the server is shut down it takes for the HttpClient
around ~20 seconds to return a proper exception such as the one in the picture.
我希望看到这个异常的速度超过 10 秒,以便能够区分服务器关闭和操作花费太长时间的情况。我在 msdn 文档中找不到任何关于此的信息。是否可以设置超时时间HttpClient
?
这是我构建的方式HttpClient
var webRequestHandler = new WebRequestHandler
{
UseProxy = false,
Proxy = null,
AllowPipelining = false,
ContinueTimeout = TimeSpan.Zero,
UseCookies = false,
AllowAutoRedirect = false,
};
var httpClient = new HttpClient(webRequestHandler);
httpClient.Timeout = timeout;
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgent);
httpClient.DefaultRequestHeaders.ExpectContinue = false;
这个答案只是扩展了@brz 的例子。
您可以使用这种不会阻塞线程的方法(Task.Wait
阻塞线程)
var timeout = Task.Delay(10000); // 10 seconds timeout
var request = httpClient.GetAsync("http://www.google.com");
await Task.WhenAny(timeout, request); // wait for either timeout or the request
if (timeout.IsCompleted) // if the timeout ended first, then handle it
{
// handle timeout
}
// otherwise continue processing the request result
var response = await request;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)