Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to return completed Task?

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?

like image 401
Andrii Avatar asked Aug 31 '25 05:08

Andrii


1 Answers

Answer from Stephen Toub (MSFT):

If you want a new Task object each time, Task.FromResult is the most efficient. Task.Delay(0) in its current implementation will return a cached task, but that's an implementation detail. If you want to use a cached task, you should cache one yourself, e.g. private static readonly Task s_completedTask = Task.FromResult(true); and then use s_completedTask.

like image 84
Andrii Avatar answered Sep 02 '25 19:09

Andrii