C# .Net 4.5 中的 Async/Await 简述
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13082074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Brief explanation of Async/Await in .Net 4.5
提问by Mayank
How does Asynchronous tasks (Async/Await) work in .Net 4.5?
异步任务 (Async/Await) 在 .Net 4.5 中如何工作?
Some sample code:
一些示例代码:
private async Task<bool> TestFunction()
{
var x = await DoesSomethingExists();
var y = await DoesSomethingElseExists();
return y;
}
Does the second awaitstatement get executed right away or after the first awaitreturns?
第二条await语句是立即执行还是在第一条语句await返回后执行?
采纳答案by Stephen Cleary
awaitpauses the method until the operation completes. So the second awaitwould get executed after the first awaitreturns.
await暂停方法直到操作完成。所以第二个await将在第一个await返回后执行。
For more information, see my async/ awaitintroor the official FAQ.
有关更多信息,请参阅 my async/ awaitintro或官方常见问题解答。
回答by nikeee
It executes after the first await returns. If this thing confuses you, try to play around with breakpoints - they are fully supported by the new async pattern.
它在第一个 await 返回后执行。如果这件事让您感到困惑,请尝试使用断点 - 新的异步模式完全支持它们。
Imagine it would look like this:
想象一下,它看起来像这样:
var x = await GetSomeObjectInstance();
var y = await GetSomeObjectInstance2(x);
There probably would occur a NullReferenceException somewhere, so the first await has toreturn first. Otherwise, xwould be null/undefined or whatever.
某处可能会发生 NullReferenceException,因此第一个 await必须首先返回。否则,x将是空/未定义或其他。
回答by rism
The methods calls will still occur sequentially just like "regular", non awaited method calls. The purpose of await is that it will return the current thread to the thread pool while the awaited operation runs off and does whatever.
方法调用仍然会像“常规”、非等待的方法调用一样按顺序发生。await 的目的是将当前线程返回到线程池,而等待的操作运行结束并执行任何操作。
This is particularly useful in high performance environments, say a web server, where a given request is processed on a given thread from the overall thread pool. If we don't await, then the given thread processing the request (and all it's resources) remains "in use" while the db / service call completes. This might take a couple of seconds or more especially for external service calls.
这在高性能环境中特别有用,例如 Web 服务器,在该环境中,在整个线程池中的给定线程上处理给定请求。如果我们不等待,那么在 db / service 调用完成时,处理请求(及其所有资源)的给定线程将保持“使用中”。这可能需要几秒钟或更长时间,尤其是对于外部服务调用。
Now in low traffic websites this is not much of an issue but in high traffic sites the cost of all these request threads just sitting around, doing nothing, in an "in-use" state, waiting for other processes like those db /service calls to return can be a resource burden.
现在在低流量网站这不是什么大问题,但在高流量网站,所有这些请求线程的成本只是坐在那里,什么都不做,处于“使用中”状态,等待其他进程,如那些 db /service 调用返回可能是一种资源负担。
We are better off releasing the thread back to the worker pool to allow it do other useful work for some other request.
我们最好将线程释放回工作池,以允许它为其他请求做其他有用的工作。
Once the db / service call completes, we can then interrupt the thread pool and ask for a thread to carry on processing that request from where it left off. At that point the state of the request is reloaded and the method call continues.
一旦 db / service 调用完成,我们就可以中断线程池并请求一个线程从它停止的地方继续处理该请求。那时请求的状态被重新加载并且方法调用继续。
So on a per request basis when using await, the request will still take the same amount of time from the users perspective... plus a tiny smidge more for the switching overhead.
因此,在使用 await 时,在每个请求的基础上,从用户的角度来看,请求仍将花费相同的时间……再加上一点点切换开销。
But in the aggregate, across all requests for all users, things can seem more performant to all users as the web server (in this case) runs more efficiently with better resource utilization. i.e. it either doesn't have to queue up requests waiting for free threads to process requests because await is returning them or alternatively we don't have to buy more hardware because we are using the same amount of hardware, more efficiently, to obtain higher throughputs.
但总的来说,在所有用户的所有请求中,由于 Web 服务器(在本例中)运行更高效,资源利用率更高,因此所有用户似乎都性能更高。即它要么不必排队等待空闲线程处理请求的请求,因为 await 正在返回它们,或者我们不必购买更多硬件,因为我们正在使用相同数量的硬件,更有效地,以获得更高的吞吐量。
There is a switching cost to this though so despite what you see in the default templates and in many docs you shouldn't just blindly use await for every single call. It's just a tool and like all tools it has its place. If the switching cost is not less than the cost of just completing your calls synchronously then you shouldn't use await.
但这有转换成本,因此尽管您在默认模板和许多文档中看到了什么,但您不应该盲目地对每次调用都使用 await。它只是一个工具,就像所有工具一样,它也有自己的位置。如果切换成本不低于同步完成调用的成本,那么您不应该使用 await。

