如果 Task<HttpResponseMessage>.IsCompleted 为真,为什么 Task<HttpResponseMessage>.Result 会抛出异常?

Why does Task<HttpResponseMessage>.Result throw an exception if Task<HttpResponseMessage>.IsCompleted is true?

这只发生在重负载下,所以我不能举一个简单的例子。这是为了系统测试,所以我试图避免等待,而是创建 2,000 个请求,然后轮询响应何时完成。

有问题的代码是:

Task<HttpResponseMessage> response = responseStatus.Item1;
if (!response.IsCompleted)
    continue;
HttpResponseMessage result = response.Result;

对 Result 的调用抛出以下内容:

System.AggregateException: One or more errors occurred.
StackTrace:       at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at SystemTests.V2.LoadTests.Test1000Requests() in C:\git\Jenova\restfulengine\SystemTests.V2\LoadTests.cs:line 121
INNER EXCEPTION:    System.Threading.Tasks.TaskCanceledException: A task was canceled.
StackTrace:    System.AggregateException: One or more errors occurred. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at SystemTests.V2.LoadTests.Test1000Requests() in C:\git\Jenova\restfulengine\SystemTests.V2\LoadTests.cs:line 121
---> (Inner Exception #0) System.Threading.Tasks.TaskCanceledException: A task was canceled.<---

2020-04-26 13:36:06,370 [MSTestAdapter Thread] WARN SystemTests.V2.LoadTests - v2/reports/19ea788d-ceb8-4a81-a974-f597494609dd failed (will retry)System.AggregateException: One or more errors occurred. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at SystemTests.V2.LoadTests.Test1000Requests() in C:\git\Jenova\restfulengine\SystemTests.V2\LoadTests.cs:line 121
---> (Inner Exception #0) System.Threading.Tasks.TaskCanceledException: A task was canceled.<---

Task.IsCompleted 是 "true if the task has completed (that is, the task is in one of the three final states: RanToCompletion, Faulted, or Canceled); otherwise, false."

因此,如果 HTTP 请求以无法创建可用 HttpResponseMessage 的方式失败,您将无法访问结果。所以检查 Task.Status 看看它是什么。