且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

死锁使用异步和放大器;等待

更新时间:2023-01-23 19:12:28

您有一个的SynchronizationContext ,并且这种情况下被抓获时,等待,这样的延续(S)可以在上下文中运行。

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

您已经开始一个异步任务,调度continutation在你的主要方面在以后的某个点运行。

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

然后,异步操作完成之前,你有code在主背景下做的异步操作的阻塞等待。延续无法安排运行,因为上下文是忙等待的延续。经典的僵局。

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.

有一些黑客,可以解决在第二个例子中的僵局,但它仍然不是你应该做的事情。要去异步整点是为了避免堵塞你的线程(S)。如果你只是去上做反正你击败的去异步的目的,任务阻塞等待。要么让一切异步的,或没有异步的,除非你没有选择。

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.