異步編程- async和await

使用目的html

避免阻塞主線程
提升程序響應能力git

C#中使用

C# 中的 Async 和 Await 關鍵字是異步編程的核心。github

運行機制

疑惑

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.web

答疑

I explain it in full in my blog post There Is No Thread.
In summary, modern I/O systems make heavy use of DMA (Direct Memory Access). There are special, dedicated processors on network cards, video cards, HDD controllers, serial/parallel ports, etc. These processors have direct access to the memory bus, and handle reading/writing completely independently of the CPU. The CPU just needs to notify the device of the location in memory containing the data, and then can do its own thing until the device raises an interrupt notifying the CPU that the read/write is complete.
Once the operation is in flight, there is no work for the CPU to do, and thus no thread.數據庫

使用場景

程序中耗時I/O操做時適合使用。
I/O操做不只包括了直接的文件、網絡的讀寫,還包括數據庫操做、Web Service、HttpRequest的調用。  編程

參考

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/index canvas

https://stackoverflow.com/questions/37419572/if-async-await-doesnt-create-any-additional-threads-then-how-does-it-make-applruby

相關文章
相關標籤/搜索