Voli
Voli

Reputation: 29

Async. programming in .Net Core

I was reading the documentation of Microsoft specifically the Async programming article and I didn't understand this section while he is explaining the work of the server's threads when using Async code.

because it(The server) uses async and await, each of its threads is freed up when the I/O-bound work starts, rather than when it finishes.

Could anyone help what does it mean by the threads r freed up when the I/O starts??

Here is the article : https://learn.microsoft.com/en-us/dotnet/standard/async-in-depth

Upvotes: 0

Views: 420

Answers (3)

Karol Rossa
Karol Rossa

Reputation: 11

When your application makes a call to an external resource like Database or HttpClient thread, that initiated connection needs to wait. Until it gets a response, it waits idly. In the asynchronous approach, the thread gets released as soon as the app makes an external call.

Here is an article about how it happens: https://medium.com/@karol.rossa/asynchronous-programming-73b4f1988cc6

And performance comparison between async and sync apporach https://medium.com/@karol.rossa/asynchronous-performance-1be01a71925d

Upvotes: 1

Here's an analogy for you: have you ever ordered at a restaurant with a large group and had someone not be ready to order when the waiter came to them? Did they bring in a different waiter to wait for him or did the waiter just come back to him after he took other people's orders?

The fact that the waiter is allowed to come back to him later means that he's freed up immediately after calling on him rather than having to wait around until he's ready.

Asynchronous I/O works the same way. When you do a web service call, for example, the slowest part (from the perspective of the client at least) is waiting for the result to come back: most of the delay is introduced by the network (and the other server), during which time the client thread would otherwise have nothing to do but wait. Async allows the client to do other things in the background.

Upvotes: 0

Stephen Cleary
Stephen Cleary

Reputation: 456437

When ASP.NET gets an HTTP request, it takes a thread from the thread pool and uses that to execute the handler for that request (e.g., a specific controller action).

For synchronous actions, the thread stays assigned to that HTTP request until the action completes. For asynchronous actions, the await in the action method may cause the thread to return an incomplete task to the ASP.NET runtime. In this case, ASP.NET will free up the thread to handle other requests while the I/O is in flight.

Further reading about the difference between synchronous and asynchronous request handling and how asynchronous work doesn't require a thread at all times.

Upvotes: 2

Related Questions