【发布时间】:2015-09-20 02:06:53
【问题描述】:
我真的很好奇 async/await 如何使您的程序不被停止。 我真的很喜欢the way how Stephen Cleary explains async/await:“我喜欢把“await”想象成一个“异步等待”。也就是说,async 方法会暂停,直到 awaitable 完成(所以它等待),但实际线程没有被阻塞(所以它是异步的)。”
我读过 async 方法会同步工作,直到编译器遇到 await 关键字。好吧。 如果编译器无法确定可等待,则编译器将等待和让出控制排队到调用方法AccessTheWebAsync 的方法。 好的。
在调用者(本例中的事件处理程序)内部,处理模式继续进行。在等待该结果之前,调用者可能会执行不依赖于来自AccessTheWebAsync 的结果的其他工作,或者调用者可能会立即等待。事件处理程序正在等待AccessTheWebAsync,而AccessTheWebAsync 正在等待GetStringAsync。来看看an msdn example:
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;
}
Another article from msdn blog 表示 async/await 不会创建新线程或使用线程池中的其他线程。好的。
我的问题:
async/await 在哪里执行可等待代码(在我们的示例中下载一个网站)导致控制权交给我们程序的下一行代码,而程序只询问
Task<string> getStringTask的结果?我们知道没有新线程,没有线程池不被使用。我的愚蠢假设是否正确,即 CLR 只是在一个线程范围内相互切换当前可执行代码和方法的可等待部分?但是更改加法的顺序并不会更改总和,并且 UI 可能会被阻塞一段时间。
【问题讨论】:
-
查看等待的不是编译器。这是编译器编译的代码。
标签: c# asynchronous async-await task-parallel-library .net-4.5