当我会用Task.Yield()? [英] When would I use Task.Yield()?

查看:225
本文介绍了当我会用Task.Yield()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用异步/等待和任务很多,但从来没有被使用 Task.Yield()而说实话,即使所有的解释,我不明白为什么我需要这个方法。

I'm using async/await and Task a lot but have never been using Task.Yield() and to be honest even with all the explanations I do not understand why I would need this method.

能有人给其中收益率()是必需的一个很好的例子?

Can somebody give a good example where Yield() is required?

推荐答案

当您使用异步 / 等待,有没有保证,你当你做等待FooAsync调用方法()实际上将异步运行。内部实现免费使用完全同步的路径返回。

When you use async/await, there is no guarantee that the method you call when you do await FooAsync() will actually run asynchronously. The internal implementation is free to return using a completely synchronous path.

如果你正在做一个API,它是重要的,你不阻止你运行一些code异步,并有一个机会,被调用的方法将同步运行(有效阻断),使用等待Task.Yield()将迫使你的方法是异步的,在这一点上返回控制。在code的其余部分将在稍后的时间执行(在这一点上,它仍然可以同步运行)在目前的情况下。

If you're making an API where it's critical that you don't block and you run some code asynchronously, and there's a chance that the called method will run synchronously (effectively blocking), using await Task.Yield() will force your method to be asynchronous, and return control at that point. The rest of the code will execute at a later time (at which point, it still may run synchronously) on the current context.

这也可以,如果你作出这样的要求有些长时间运行的初始化,异步方法是有用的,即:

This can also be useful if you make an asynchronous method that requires some "long running" initialization, ie:

 private async void button_Click(object sender, EventArgs e)
 {
      await Task.Yield(); // Make us async right away

      var data = ExecuteFooOnUIThread(); // This will run on the UI thread at some point later

      await UseDataAsync(data);
 }

如果没有 Task.Yield()调用,该方法将同步执行所有的方式,以第一次调用等待

Without the Task.Yield() call, the method will execute synchronously all the way up to the first call to await.

这篇关于当我会用Task.Yield()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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