tntwyckoff
tntwyckoff

Reputation: 539

ASPNET Core and async execution

I'm still trying to get my head around how and when to use async methods in asp.net, and i could ask a dozen questions about it, but this behavior is surprising to me...from everything i've read if i create a an async method but declare it as a void, and then do not await it, it's essentially as if you just ran that async code on a worker thread without hanging around to get a result. that is, the void would return immediately to the caller, the caller would go about it's business, and potentially complete before the async method does. but in my .net core application, that is definitely not the case. i have an async void that i call from inside another async method and though i don't await it the threads blocks on the async code. what's happening here?

thanks.

Upvotes: 1

Views: 3101

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457217

I'm still trying to get my head around how and when to use async methods in asp.net

You'd use them when:

  1. You have asynchronous work to do. Generally speaking, this means I/O-bound, not CPU-bound.
  2. Your backend scales. E.g., it's a WebAPI, NoSQL service, SQL Server cluster, etc. If your backend is a single SQL Server instance, it's not scalable, and there's no point to using asynchrony on your web tier.

it's essentially as if you just ran that async code on a worker thread

No. async void just prevents the caller from detecting when it's complete. It still runs in the same context as the caller, just like an async Task method would.

the threads blocks on the async code

It's likely that your "async" code is actually synchronous. If it doesn't have an await, then the compiler will warn you that it's synchronous.


You may find my intro to async blog post and async on ASP.NET MSDN article helpful. As far as async goes, ASP.NET Core only changed a couple things: 1) There's no more ASP.NET request context, and 2) The entire pipeline is async-compatible, so things like async filters and async view components just work.

Upvotes: 7

Related Questions