Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c# - async-await threading internals

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...