Reputation: 1017
ASP.NET Core does not have Synchronization context, which will allow blocking asynchronous methods without deadlocks.
public void Save(entity)
{
if (_repository.ExistsAsync(entity.Name).Result)
{
_repository.SaveNewAsync(entity).Wait();
}
}
I came to ASP.NET Core from the full .NET framework where you were forced to use async-await
everywhere because of possible deadlocks. So, reading a code, which blocks asynchronous methods, makes me feel uncomfortable. But I cannot come up with arguments against blocking code, because it works.
Question: What are the possible disadvantages of blocking asynchronous code in ASP.NET Core?
Upvotes: 0
Views: 271
Reputation: 239636
async
/await
was introduced to try to help people unlock the power of asynchronous code without all of the callback-spaghetti when promises (Task
s) are explicitly used. It was recognition that, in order to eke the best performance out of our systems, we have to make asynchronous activity first-class.
async
/await
work best when you're not tied to any kind of single-threaded (or logical equivalent) context; Instead where any thread is as good as any other, for completing work that is now ready to be worked on. If there is some "blessed" thread (the UI thread) or some synchronization requirement (ASP.Net's Session and various other Contexts), you can easily end up queueing work, just in case it needs to take advantage of those contexts (although you can of course try to opt out via ConfigureAwait
if you are using async
).
Asp.Net core was a rebuild of the concept of Asp.Net but without so much implicit context and to allow it to become "free-threaded". This was to allow us to take full advantage of the power of async.
It wasn't made free-threaded just so that we could block threads. That you can now write code in asp.net core that would have deadlocked "classic" asp.net isn't a license to write such code. It's still not a good idea.
Upvotes: 1