我什么时候会使用 Task.Yield()? [英] When would I use Task.Yield()?

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

问题描述

我经常使用 async/await 和 Task 但从来没有使用过 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.

有人可以举一个需要 Yield() 的好例子吗?

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

推荐答案

当你使用 async/await 时,并不能保证你调用时调用的方法await 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,你不阻塞并且异步运行一些代码,并且被调用的方法有可能同步运行(有效阻塞),使用 await Task.Yield() 将强制您的方法异步,并在此时返回控制权.其余代码稍后将在当前上下文中执行(此时仍可能同步运行).

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() 调用,该方法将一直同步执行,直到第一次调用 await.

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天全站免登陆