我在测试代码中写了这段代码,但是抛出的One or more errors occurred. (A task was canceled.)
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()
{
BaseAddress = new Uri("https://www.taobao.com"),
Timeout = TimeSpan.FromMilliseconds(10)
};
Assert.Throws<TimeoutException>(() =>
{
var s = client.GetAsync("").Result;
});
Assert.Throws() Failure
Expected: typeof(System.TimeoutException)
Actual: typeof(System.AggregateException): One or more errors occurred. (A task was canceled.)
大家在代码中都是如何捕获这个错误的呢?
Github上的讨论:
HttpClient throws TaskCanceledException on timeout
StackOverflow上的讨论:
How can I tell when HttpClient has timed out?
HttpClient.Timeout 属性的帮助文档:
//
// Summary:
// Gets or sets the timespan to wait before the request times out.
//
// Returns:
// The timespan to wait before the request times out.
//
// Exceptions:
// T:System.ArgumentOutOfRangeException:
// The timeout specified is less than or equal to zero and is not System.Threading.Timeout.InfiniteTimeSpan.
//
// T:System.InvalidOperationException:
// An operation has already been started on the current instance.
//
// T:System.ObjectDisposedException:
// The current instance has been disposed.
Timeout 设置只是的是一个等待时间,Timeout = TimeSpan.FromMilliseconds(10)
只是表示等10秒,如果超过 10 秒就取消当前的 Task ,实际 TCP 层面没有发生超时。
在这样的情况下,对于 HttpClient 来说就是我等了10秒钟你没来,我走人,我根本不知道你为什么没来,你让 HttpClient 报什么更有用的异常?
如果你想捕捉到 tcp 层面的超时异常,需要把 HttpClient.Timeout 的值设置为大于等于 tcp 的超时时间
@dudu: 确实没想到 tcp层面的超时,我去了解一下。[飞吻]
dudu 太强了!