返回已完成任务的最佳方法是什么? [英] What is the best way to return completed Task?
问题描述
返回已完成的 任务
对象?
What is the best way to return a completed Task
object?
可以编写 Task.Delay(0)
或 Task.FromResult< bool>(true)
之类的。
It is possible to write Task.Delay(0)
, or Task.FromResult<bool>(true)
whatever.
但是最有效的方法是什么?
But what is the most efficient way?
推荐答案
任务。 FromResult将是最直接的。它还包括一些通用整数等的内建结果。但是,如果您的值不是显而易见的值(并且不会进行内建处理),但很可能在您的方案中经常返回-那么您可以创建自己的值将结果缓存在一个字段中(如果合适的话,可以是静态的)-但是缓存Task而不是结果本身很重要。l-否则每次都使用Task.FromResult。
Task.FromResult would be the most direct. It also includes inbuilt results for a few common integers etc. However, if your value is not an "obvious" value (and won't have inbuilt handling) but is likely to be returned often in your scenario - then you can create your own cached result in a field (maybe static if appropriate) - but it is important to cache the Task, not the result itself.l - otherwise just use Task.FromResult each time.
这篇关于返回已完成任务的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!