我正在阅读 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;
}
该页面还说:
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
这种“不创建额外线程”是否适用于标记为异步的方法范围内?
我想,为了让 GetStringAsync 和 AccessTheWebAsync 同时运行(否则 GetStringAsync 将永远不会完成,因为 AccessTheWebAsync 现在拥有控制权),最终 GetStringAsync 必须在与 AccessTheWebAsync 的线程不同的线程上运行。
对我来说,编写异步方法仅在等待的方法也是异步的(它已经使用额外的线程来并行执行自己的事情)时不添加更多线程时才有用
我的理解正确吗?
最佳答案
这是 async
强大功能的关键。 GetStringAsync
和其他自然异步操作不需要线程。 GetStringAsync
只是发出 HTTP 请求并注册一个回调以在服务器回复时运行。不需要一个线程来等待服务器响应。
实际上,线程池只用了一点点。在上面的示例中,由 GetStringAsync
注册的回调将在线程池线程上执行,但它所做的只是通知 AccessTheWebAsync
它可以继续执行。
我有一个 async
intro blog post您可能会发现有帮助。
关于c# 异步运行单线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17734420/