异步等待线程内部线程

2023-09-03 00:21:59 作者:不爱像缺氧i

我很好奇异步等待线程内部。

每个人都指出,异步是好多情况下的性能,因为它释放正在等待以久的异步调用的响应线程。 好吧,我得到它。

不过,让我们考虑这种情况。

我有一个异步的methodA在数据库中执行异步操作。 数据库的API公开功能BeginQuery和事件QueryCompleted。 我的包裹与任务(与使用TaskCompletionSource的)。

我的问题是,到底是怎么回事引擎盖下调用BeginQuery和射击事件QueryCompleted之间。

我的意思是 - 没有它需要生成一些工人来触发事件?在非常低的水平也必须是阻止来自分贝线程读取结果的一些同步循环。

我的猜想是,任何异步调用必须产生一个线程来实际处理响应(也许等待它在低C级的驱动程序code ++循环)。

所以我们唯一的收获是调用者线程可以在其他线程正在做的工作中解放出来。

是否调用一个异步方法总是创建一个新的工作线程?

有人可以证实我的理解?

解决方案   

每个人都指出,异步的情况下的表现好多了,因为它释放正在等待以久的异步调用的响应线程。

是的,没有。后面点异步是释放调用线程。在UI应用程序中,异步的主要优点是响应性,因为UI线程被释放。在服务器应用中,的主要好处异步是可扩展性,因为请求的线程被释放,以处理其他请求。

  

所以我们唯一的收获是调用者线程可以在其他线程正在做的工作中解放出来。   是否总是调用一个异步方法是创建一个新的工作线程?

没有。在操作系统级别,所有的I / O是异步的。它是同步的API其中阻塞线程而底层异步I / O正在进行中。我最近写了这个在一篇博客文章:没有线程

I'm curious about async await threading internals.

C 11多线程 一 线程创建,等待,异步

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?

解决方案

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.

 
精彩推荐
图片推荐