c #async运行单线程?

use*_*144 7 c# async-await c#-5.0

我正在阅读http://msdn.microsoft.com/en-US/library/vstudio/hh191443.aspx.示例代码:

async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync. 
    //  - AccessTheWebAsync can't continue until getStringTask is complete. 
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
    //  - Control resumes here when getStringTask is complete.  
    //  - The await operator then retrieves the string result from getStringTask. 
    string urlContents = await getStringTask;

    // The return statement specifies an integer result. 
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
    return urlContents.Length;
}
Run Code Online (Sandbox Code Playgroud)

该页面还说:

async和await关键字不会导致创建其他线程.异步方法不需要多线程,因为异步方法不能在自己的线程上运行

这个"没有创建额外的线程"是否适用于标记为async的方法的范围?

我想,为了让GetStringAsync和AccessTheWebAsync同时运行(否则GetStringAsync将永远不会像AccessTheWebAsync现在拥有的那样完成),最终GetStringAsync必须在与AccessTheWebAsync的线程不同的线程上运行.

对我来说,编写异步方法仅在不等待添加更多线程时才有用,因为它等待的方法也是异步的(已经使用额外的线程并行执行它自己的事情)

我的理解是否正确?

Ste*_*ary 13

这是力量的关键async.GetStringAsync和其他自然异步操作不需要线程.GetStringAsync只需发出HTTP请求并注册一个回调,以便在服务器回复时运行.只需等待服务器响应就不需要线程.

实际上,线程池只使用了一小部分.在上面的示例中,注册的回调GetStringAsync将在线程池线程上执行,但它所做的只是通知AccessTheWebAsync它可以继续执行.

我有一个你可能会觉得有用的async介绍博客文章.