C# Async await deadlock problem gone in .NetCore?

Viewed 3060

In .NetFramework there was a high risk of a deadlock occuring when synchronizing to the synchronization context using:

var result =  asyncMethod().Result; 
var result =  asyncMethod().GetAwaiter().GetResult();

instead of

var result = await asyncMethod();

(read Stephen Cleary blogpost for more info)

Since the synchronization context has been removed in .NetCore. Does this mean that the above methods are now safe to use?

2 Answers

Yes and no. It's true that there's no synchronization context in .NET Core, and thereby, one of the major sources of deadlock issues has been eliminated. However, this doesn't mean that deadlocks are totally impossible. Regardless, you should not let good programming practices slide, just because it may not be a big issue in one circumstance any more. ASP.NET Core, in particular, is fully async, so there is no reason to ever use a sync version of a method or simply block on an async task. Use await as you always would and should.

You Can Block on Async Code - But You Shouldn’t

The first and most obvious consequence is that there’s no context captured by await. This means that blocking on asynchronous code won’t cause a deadlock. You can use Task.GetAwaiter().GetResult() (or Task.Wait or Task.Result) without fear of deadlock. However, you shouldn’t. Because the moment you block on asynchronous code, you’re giving up every benefit of asynchronous code in the first place. The enhanced scalability of asynchronous handlers is nullified as soon as you block a thread. There were a couple of scenarios in (legacy) ASP.NET where blocking was unfortunately necessary: ASP.NET MVC filters and child actions. However, in ASP.NET Core, the entire pipeline is fully asynchronous; both filters and view components execute asynchronously. In conclusion, ideally you should strive to use async all the way; but if your code needs to, it can block without danger.

-Extract from blogpost by Stephen Cleary

Credit to GSerg for finding the post

However, you might encounter thread pool starvation

http://labs.criteo.com/2018/10/net-threadpool-starvation-and-how-queuing-makes-it-worse/

Related