我在读http://msdn.microsoft.com/en-US/library/vstudio/hh191443.aspx。 示例代码:c#异步运行单线程?
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;
}
该页面还表示:
异步和等待关键字不会导致创建额外的线程。异步方法不需要多线程,因为异步方法不会在其自己的线程上运行
是否在标记为异步的方法范围内应用此“没有附加线程”?
我会想象为了GetStringAsync和AccessTheWebAsync同时运行(否则GetStringAsync将永远不会完成,因为AccessTheWebAsync现在有控制权),最终GetStringAsync必须从AccessTheWebAsync的线程运行在不同的线程上。
对我来说,写异步方法在不增加时,它等待的方法也更异步线程(已使用额外的线程做自己的事并行)
我的理解是否正确才是有用的?
你能解释一下“自然异步操作不需要线程”是什么意思吗?如何处理这项工作?你在谈论单个线程在任务中分配的时间吗? –
@VincePanuccio:在评论中描述有点长,但我有[博客文章](http://blog.stephencleary.com/2013/11/there-is-no-thread.html)详情。 –