7

The danger of async/await and .Result in one picture

 3 years ago
source link: https://tooslowexception.com/the-danger-of-asyncawait-and-result-in-one-picture/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The danger of async/await and .Result in one picture

Sync over async in .NET is always bad and there is no better advice than just to avoid it. What does “Sync over async” mean exactly? It happens if you synchronously wait on an asynchronous operation result with the help of .Result, .Wait or similar. Why is it bad? First of all, it blocks (wastes) one thread to wait on a result – which may lead to threads starvation. But even worse, it may deadlock your operation and (sometimes) the whole application.

Probably you’ve heard all that previously. I just wanted to present a picture, “worth a thousand words“, to explain why does it happen.

synchronizationcontext_winforms_nestedsync
There is a concept of SynchronizationContext in .NET – an abstraction that knows how/where schedule a work item (like an async/await continuation). When you await something, SynchronizationContext is being captured. And when continuation is going to be run – we use SynchronizationContext to run the continuation “somewhere”. SynchronizationContext implementation may be different in various scenarios (console, UI, web, mobile applications), because there are various needs to “synchronize” work items. The main example is a GUI-based application. When we start an asynchronous operation on the UI thread, we expect its continuations will “return” to the same thread.

But, if we .Result that operation, the main UI thread is blocked waiting on the result, so it is not able to process anything (including mouse/keyboard events). So there is no way continuation (that would set the result) may run, thus we endlessly wait for the result – deadlock.

synchronizationcontext_winforms_configureawait

That’s why ConfigureAwait helps – it allows to say “I don’t care about scheduling continuation to the original (captured) context“. Thanks to that asynchronous operation continuation is scheduled to a different thread (thread pool’s) and sets the result with no problem. This resumes the main UI thread, and there is no deadlock.

That was just two simple drawings. If you’d like to know more, refer to a great ConfigureAwait FAQ by Stephen Toub.

Again, all this is just a work for a much bigger project, which is awesome Async Expert on-line course about asynchronous and concurrent programming in .NET. If you found it interesting, stay tuned by subscribing to the newsletter on the above-mentioned page!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK