使用 async/await 是否会创建一个新线程? [英] Does the use of async/await create a new thread?

查看:127
本文介绍了使用 async/await 是否会创建一个新线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 TPL 的新手,我想知道:新的异步编程支持如何到 C# 5.0(通过新的 asyncawait 关键字)与线程的创建有关吗?

I am new to TPL and I am wondering: How does the asynchronous programming support that is new to C# 5.0 (via the new async and await keywords) relate to the creation of threads?

具体来说,async/await 的使用是否会在每次使用时创建一个新线程?如果有许多使用 async/await 的嵌套方法,是否为每个方法都创建了一个新线程?

Specifically, does the use of async/await create a new thread each time that they are used? And if there many nested methods that use async/await, is a new thread created for each of those methods?

推荐答案

简而言之NO

来自 使用 Async 和 Await 进行异步编程:线程

async 和 await 关键字不会导致额外的线程创建.异步方法不需要多线程,因为异步方法不在自己的线程上运行.该方法在当前运行同步上下文并仅在线程上使用时间方法是主动的.您可以使用 Task.Run 将受 CPU 限制的工作移至后台线程,但后台线程对进程没有帮助这只是在等待结果可用.

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. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

这篇关于使用 async/await 是否会创建一个新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆