Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm curious about async await threading internals.

Everyone states that async is so much better in case of performance, because it frees threads that are waiting for a response to a long asynchronous call. Ok I get it.

But let's consider this scenario.

I have an async methodA executing an async operation on database. The api of the database exposes function BeginQuery and event QueryCompleted. I wrapped those with a task (with use of TaskCompletionSource).

My question is what is going under the hood between calling BeginQuery and firing event QueryCompleted.

I mean - doesn't it need to spawn some kind of worker to fire the event? At the very low level it must be some synchronous loop that is blocking a thread reading result from db.

What I suppose is that any async call must generate a thread to actually handle the response (maybe wait for it in a low level c++ loop in driver code).

So our only "gain" is that the caller thread can be freed when some other thread is doing its work.

Does calling an asynchronous method always create a new worker thread?

Could someone confirm my understanding?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
199 views
Welcome To Ask or Share your Answers For Others

1 Answer

Everyone states that async is so much better in case of performance, because it frees threads that are waiting for a response to a long asynchronous call.

Yes and no. The point behind async is to free up the calling thread. In UI applications, the primary benefit of async is responsiveness, because the UI thread is freed up. In server applications, the primary benefit of async is scalability, because the request thread is freed up to handle other requests.

So our only "gain" is that the caller thread can be freed when some other thread is doing its work. Does always calling an asynchronous method is creating a new worker thread?

No. At the OS level, all I/O is asynchronous. It is the synchronous APIs which block a thread while the underlying asynchronous I/O is in progress. I recently wrote this up in a blog post: there is no thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...