An async/await example that causes a deadlock

后端 未结 5 1919
暗喜
暗喜 2020-11-21 13:32

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

5条回答
  •  不思量自难忘°
    2020-11-21 14:08

    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_Click for UI / MyController.Get for ASP.NET):

    1. The top-level method calls GetJsonAsync (within the UI/ASP.NET context).

    2. GetJsonAsync starts the REST request by calling HttpClient.GetStringAsync (still within the context).

    3. GetStringAsync returns an uncompleted Task, indicating the REST request is not complete.

    4. GetJsonAsync awaits the Task returned by GetStringAsync. The context is captured and will be used to continue running the GetJsonAsync method later. GetJsonAsync returns an uncompleted Task, indicating that the GetJsonAsync method is not complete.

    5. The top-level method synchronously blocks on the Task returned by GetJsonAsync. This blocks the context thread.

    6. ... Eventually, the REST request will complete. This completes the Task that was returned by GetStringAsync.

    7. The continuation for GetJsonAsync is now ready to run, and it waits for the context to be available so it can execute in the context.

    8. Deadlock. The top-level method is blocking the context thread, waiting for GetJsonAsync to complete, and GetJsonAsync is 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!

提交回复
热议问题