I came across some best practices for asynchronous programming using c#\'s async/await keywords (I\'m new to c# 5.0).
One of the advices gi
Take a look at this example, Stephen has a clear answer for you:
So this is what happens, starting with the top-level method (
Button1_Clickfor UI /MyController.Getfor ASP.NET):
The top-level method calls
GetJsonAsync(within the UI/ASP.NET context).
GetJsonAsyncstarts the REST request by callingHttpClient.GetStringAsync(still within the context).
GetStringAsyncreturns an uncompletedTask, indicating the REST request is not complete.
GetJsonAsyncawaits theTaskreturned byGetStringAsync. The context is captured and will be used to continue running theGetJsonAsyncmethod later.GetJsonAsyncreturns an uncompletedTask, indicating that theGetJsonAsyncmethod is not complete.The top-level method synchronously blocks on the
Taskreturned byGetJsonAsync. This blocks the context thread.... Eventually, the REST request will complete. This completes the
Taskthat was returned byGetStringAsync.The continuation for
GetJsonAsyncis now ready to run, and it waits for the context to be available so it can execute in the context.Deadlock. The top-level method is blocking the context thread, waiting for
GetJsonAsyncto complete, andGetJsonAsyncis waiting for the context to be free so it can complete. For the UI example, the "context" is the UI context; for the ASP.NET example, the "context" is the ASP.NET request context. This type of deadlock can be caused for either "context".
Another link you should read: Await, and UI, and deadlocks! Oh my!