Deadlock using async & await

前端 未结 1 1356
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 02:28

I want my program to follow this callstack/workflow:

  1. dispatch()
  2. authorize()
  3. httpPost()

相关标签:
1条回答
  • 2020-12-04 03:05

    You have a SynchronizationContext, and that context is being captured when you await so that the continuation(s) can run in that context.

    You're starting an async task, scheduling a continutation to run in your main context at some later point.

    Then, before the async operation is done, you have code in your main context doing a blocking wait on the async operation. The continuation cannot be scheduled to run because the context is busy waiting on the continuation. Classic deadlock.

    This is why it's important to "async all the way up", as you did in your first example.

    There are a few hacks that can work around the deadlock in the second example, but it's still not something you should be doing. The entire point of going asynchronous is to avoid blocking your thread(s). If you just go doing a blocking wait on the task anyway you're defeating the purpose of going asynchronous. Either make everything asynchronous, or nothing asynchronous, unless you don't have a choice.

    0 讨论(0)
提交回复
热议问题