是否“等待Task.CompletedTask"?做任何事情? [英] Does "await Task.CompletedTask" do anything?

查看:83
本文介绍了是否“等待Task.CompletedTask"?做任何事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此声明感到好奇:

等待Task.CompletedTask;

我知道它名义上并没有做任何实际的事情,但是我想知道的是它是否实际上导致正在运行的函数退出,然后在等待之后在语句处继续执行,或者它是否真的什么也不做呢?根本不打断线程.

I know that it nominally doesn't do anything practical, but what I'm wondering is whether it actually causes the running function to exit, then resume at the statement after the await, or whether it truly does nothing and doesn't interrupt the thread at all.

从某种意义上说,这可能会导致当前的运行循环完成并恢复,如果运行循环是主线程,则意味着UI更改已提交.

This might make a difference in the sense that it would cause the current run loop to complete and resume, and if the run loop is the main thread it would mean that UI changes got committed.

文档中没有对此进行解释,因此我无法确定决定它是什么的好方法.

The documentation doesn't explain it, and I can't figure out a good way to decide which it is.

谢谢,弗兰克

推荐答案

它是否实际上导致正在运行的函数退出,然后在等待之后在语句处继续执行,或者它是否确实不执行任何操作并且根本不会中断线程.

whether it actually causes the running function to exit, then resume at the statement after the await, or whether it truly does nothing and doesn't interrupt the thread at all.

await 将首先测试其awaitable查看它是否已经完成,如果已经完成,它将继续同步执行.

await will first test its awaitable to see if it is already complete, and if it is, it will continue executing synchronously.

如果要强制产生一个异步函数,请使用 await Task.Yield(); .旁注:这在生产代码中应该很少见,但有时对单元测试很有用.

If you want to force an asynchronous function to yield, then use await Task.Yield();. Side note: this should be extremely rare in production code, but it's sometimes useful for unit tests.

这篇关于是否“等待Task.CompletedTask"?做任何事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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