在 C# 中等待异步如何工作 [英] How does await async work in C#

查看:30
本文介绍了在 C# 中等待异步如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解 await async 在 C# 中是如何工作的,有一件事让我很困惑.我知道任何使用 await 关键字的方法都必须用 async 标记.我的理解是,当遇到带有 await 关键字的行时,不会执行该行下方的代码.启动异步操作以执行 await 行中的语句,并将控制权返回给调用方法,该方法可以继续执行.

I am trying to understand how await async work in C# and one thing is confusing me a lot. I understand that any method that uses await keyword must be marked with async. My understanding is that when a line with await keyword is hit the code below that line is not executed. An async operation is started to carry on the statement in the await line and the control is returned to the calling method which can proceed with the execution.

问题 1:这个假设是否正确,或者 await 关键字下面的代码仍在执行?

Question # 1: Is this assumption correct or the code below the await keyword is still executed?

第二个假设我调用了一个服务方法 async 并且需要返回它的结果.return 语句位于 await 关键字下方.

Secondly suppose I called a service method async and need to return its result. The return statement is below the await keyword.

问题 2:什么时候命中 return 语句,在异步调用完成之后还是之前?

Question # 2: When is the return statement hit, after the async call has completed or before it?

问题 3:我想使用该服务调用的结果,而异步操作无济于事,因为我希望在返回结果时命中调用方法.我知道这可以使用使调用同步的 Result 属性来完成.但是,在 DB 操作中使用 async 有什么用呢?因为它们实际上在大多数应用中占用了 80% 的时间.

Question # 3: I want to use the result of that service call and async operation wont help cause I want the calling method to be hit when the result has been returned. I understand this can be done using the Result property which makes the call synchronus. But then what is the use of async in DB operations cause they are the ones that actually take 80% of the time in most apps.

问题#4:如何将异步用于数据库操作?是否可行并推荐?

Question # 4: How can I use async with DB operations? Is it possible and recomended?

问题#5:异步操作在哪些场景中有用,似乎每个api现在都在无缘无故地进行异步操作?还是我错过了使用异步操作的重点?

Question # 5: In which scenraio will async operations be useful it seems that every api is just making async operations now without a reason? or did I miss the point of using async ops?

我的意思是说 api 无缘无故地创建异步方法是因为方法必须返回一些东西,直到进行计算,它们如何才能返回,所以从本质上讲,调用不会仍然阻塞,因为它会在返回结果之前是没有用的吗?

What I mean by saying that api are making asyn methods without a reason is because methods have to return something and untill that calculation is made how can they return so in essense won't the call be still blocking in sense that it will be useless until result is returned?

推荐答案

MSDN 解释一切.

我理解,虽然有时普通文档(特别是来自 MSDN)可能难以适用于您的特定情况,所以让我们回顾一下您的观点.

I understand though that sometimes vanilla docs (particularly from MSDN) can be difficult to apply to your particular situation, so let's go over your points.

问题 1:这个假设是否正确,或者 await 关键字下面的代码仍在执行?

Question # 1: Is this assumption correct or the code below the await keyword is still executed?

await"关键字下面的代码只会在异步调用完成时执行.同时,由于您的方法被标记为异步",因此在您的方法完成之前,控制权将返回给您的方法的调用者.来自上面的 MSDN 链接:

The code below the "await" keyword will only be executed when the async call completes. In the meantime, since your method is marked "async", control will be returned to the caller of your method until your method completes. From the MSDN link above:

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;

我认为这些评论很有解释性.

I think the comments are quite explanatory.

第二个假设我调用了一个服务方法 async 并且需要返回它的结果.return 语句位于 await 关键字下方.

Secondly suppose I called a service method async and need to return its result. The return statement is below the await keyword.

问题 2:什么时候命中 return 语句,在异步调用完成之后还是之前?

Question # 2: When is the return statement hit, after the async call has completed or before it?

之后.

问题 3:我想使用该服务调用的结果,而异步操作无济于事,因为我希望在返回结果时命中调用方法.我知道这可以使用使调用同步的 Result 属性来完成.但是,在 DB 操作中使用 async 有什么用呢?因为它们实际上在大多数应用中占用了 80% 的时间.

Question # 3: I want to use the result of that service call and async operation wont help cause I want the calling method to be hit when the result has been returned. I understand this can be done using the Result property which makes the call synchronus. But then what is the use of async in DB operations cause they are the ones that actually take 80% of the time in most apps.

假设您需要进行三个不相关的数据库查询来完成您的服务,然后根据结果进行计算,然后完成.如果您按顺序执行此操作,则必须等到每个操作完成.如果您使用异步调用,那么 C# 将并行运行三个查询,您的服务可能会更快完成.

Suppose you need to make three unrelated DB queries to complete your service, then perform a calculation based on the results, then finish. If you did this sequentially, you'd have to wait until each operation completes. If you use async calls, then C# will run the three queries in parallel and your service might finish much sooner.

此外,返回 Task 的操作可以用作 Futures.请参阅 MSDN on Futures,其中讨论了有关如何并行化基于工作的几种模式期货并合并结果.

Also, operations that return Task can be used as Futures. See MSDN on Futures where several patterns are discussed on how to parallelize work based on futures and merge the results.

如果你的服务只需要一个数据库调用,那么你调用它异步肯定会更糟糕.

If your service only needs one DB call then it will definitely be worse for you to call it async.

问题#4:如何将异步用于数据库操作?是否可行并推荐?

Question # 4: How can I use async with DB operations? Is it possible and recomended?

ADO.NET 现在包括异步方法 ReadAsync 和 NextResultAsync.

ADO.NET now includes async methods ReadAsync and NextResultAsync .

这绝对是可能的,至于推荐,这个讨论比我写的要完整得多这里.

It is definitely possible, as for recommended this discussion is much more complete than I could write here.

问题#5:异步操作在哪些场景中有用,似乎每个api现在都在无缘无故地进行异步操作?还是我错过了使用异步操作的重点?

Question # 5: In which scenraio will async operations be useful it seems that every api is just making async operations now without a reason? or did I miss the point of using async ops?

异步操作对于轻松并行化任何长时间运行的操作非常有用,而不会遇到线程问题.如果你的方法只做一件事,或者一系列简单(快速)的事情,那么是的,异步是没用的.但是,如果您有多个长时间运行的操作,那么通过异步并行化它们比管理线程要容易得多且不易出错.

async operations are very useful to easily parallelize any long running operations without running into threading problems. If your method only does one thing, or a sequence of simple (fast) things, then yes it is useless to go async. However if you have more than one long running operations, it is far easier and less error prone to parallelize them via async than it is to do it managing threads.

这篇关于在 C# 中等待异步如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆