在没有中间工作的情况下将await与异步方法一起使用会有什么好处? [英] Is there any benefit in using await with an async method without intermediate work?

查看:107
本文介绍了在没有中间工作的情况下将await与异步方法一起使用会有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN 使用以下示例:

async Task<int> AccessTheWebAsync()
{ 
    HttpClient client = new HttpClient();
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    DoIndependentWork();

    string urlContents = await getStringTask;

    return urlContents.Length;
}

因此,GetStringAsync方法基本上可以保证将来会在某个时候返回字符串类型的Task,但是到DoIndependentWork调用时,getString尚未成为awaited,因此它可以继续做其他工作,直到发生这种情况为止.

So the GetStringAsync method will basicallly promise to return a Task of type string at some point in the future, but by the time DoIndependentWork is called, getString hasn't been awaited yet so it can continue to do other work until this happens.

但是文档然后说

如果AccessTheWebAsync没有任何它可以做的工作 调用GetStringAsync并等待其完成,您可以简化 您的代码,只需在以下单个语句中调用并等待即可.

If AccessTheWebAsync doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.

string urlContents = await client.GetStringAsync();

如果您只是想马上等待某件事,这样做是否有任何好处?还是只是为了在应用程序开发时预先准备使用异步?

Is there any benefit to doing this at all if you're just going to await something straight away? Or is it just so you're preparing in advance to use asynchrony as your applications develops?

推荐答案

主要优点是await <some-operation-that-does-I/O>不会在等待中占用线程,从而提高了资源利用率.仅在I/O完成时才调试线程.与等待线程相比,您在系统上可以拥有更多未完成的I/O请求. Stephen Cleary在这篇文章中对此进行了详细说明比我雄辩地雄辩.

The main advantage is that await <some-operation-that-does-I/O> doesn't tie up a thread in a wait, improving resource utilization. A thread will only be commissioned when the I/O completes. You can have many more outstanding I/O requests on a system than you can have waiting threads. Stephen Cleary has an article on this that explains it more eloquently than I can.

这篇关于在没有中间工作的情况下将await与异步方法一起使用会有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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