You are misusing the API.
Here's the situation: in ASP.NET, only one thread can handle a request at a time. You can do some parallel processing if necessary (borrowing additional threads from the thread pool), but only one thread would have the request context (the additional threads do not have the request context).
This is managed by the ASP.NET SynchronizationContext
.
By default, when you await
a Task
, the method resumes on a captured SynchronizationContext
(or a captured TaskScheduler
, if there is no SynchronizationContext
). Normally, this is just what you want: an asynchronous controller action will await
something, and when it resumes, it resumes with the request context.
So, here's why test5
fails:
Test5Controller.Get
executes AsyncAwait_GetSomeDataAsync
(within the ASP.NET request context).AsyncAwait_GetSomeDataAsync
executes HttpClient.GetAsync
(within the ASP.NET request context).HttpClient.GetAsync
returns an uncompleted Task
.AsyncAwait_GetSomeDataAsync
awaits the Task
; since it is not complete, AsyncAwait_GetSomeDataAsync
returns an uncompleted Task
.Test5Controller.Get
blocks the current thread until that Task
completes.Task
returned by HttpClient.GetAsync
is completed.AsyncAwait_GetSomeDataAsync
attempts to resume within the ASP.NET request context. However, there is already a thread in that context: the thread blocked in Test5Controller.Get
.Here's why the other ones work:
test1
, test2
, and test3
): Continuations_GetSomeDataAsync
schedules the continuation to the thread pool, outside the ASP.NET request context. This allows the Task
returned by Continuations_GetSomeDataAsync
to complete without having to re-enter the request context.test4
and test6
): Since the Task
is awaited, the ASP.NET request thread is not blocked. This allows AsyncAwait_GetSomeDataAsync
to use the ASP.NET request context when it is ready to continue.And here's the best practices:
async
methods, use ConfigureAwait(false)
whenever possible. In your case, this would change AsyncAwait_GetSomeDataAsync
to be var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
Task
s; it's async
all the way down. In other words, use await
instead of GetResult
(Task.Result
and Task.Wait
should also be replaced with await
).That way, you get both benefits: the continuation (the remainder of the AsyncAwait_GetSomeDataAsync
method) is run on a basic thread pool thread that doesn't have to enter the ASP.NET request context; and the controller itself is async
(which doesn't block a request thread).
More information:
async
/await
intro post, which includes a brief description of how Task
awaiters use SynchronizationContext
.SynchronizationContext
restricts the request context to just one thread at a time.Update 2012-07-13: Incorporated this answer into a blog post.