我正在阅读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;
}
该页面还说:
async 和 await 关键字不会导致创建额外的线程。异步方法不需要多线程,因为异步方法不在自己的线程上运行
这个“没有创建额外的线程”是否适用于标记为异步的方法范围内?
我想为了让 GetStringAsync 和 AccessTheWebAsync 同时运行(否则 GetStringAsync 将永远无法完成,因为 AccessTheWebAsync 现在拥有控制权),最终 GetStringAsync 必须在与 AccessTheWebAsync 线程不同的线程上运行。
对我来说,编写异步方法仅在它等待的方法也是异步的时候不添加更多线程有用(它已经使用额外的线程并行地做自己的事情)
我的理解正确吗?