What is the best way to return a completed Task
object?
It is possible to write Task.Delay(0)
, or Task.FromResult<bool>(true)
whatever.
But what is the most efficient way?
What is the best way to return a completed Task
object?
It is possible to write Task.Delay(0)
, or Task.FromResult<bool>(true)
whatever.
But what is the most efficient way?
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.
Here's a little demo which shows the difference in exception handling between methods marked and not marked with async.
Moved (and edited) from When async Task<T> required by interface, how to get return variable without compiler warning)
Answer from Stephen Toub (MSFT):