What is the use for Task.FromResult<TResult> in C#

lysergic-acid picture lysergic-acid · Oct 24, 2013 · Viewed 86.5k times · Source

In C# and TPL (Task Parallel Library), the Task class represents an ongoing work that produces a value of type T.

I'd like to know what is the need for the Task.FromResult method ?

That is: In a scenario where you already have the produced value at hand, what is the need to wrap it back into a Task?

The only thing that comes to mind is that it's used as some adapter for other methods accepting a Task instance.

Answer

Stephen Cleary picture Stephen Cleary · Oct 31, 2013

There are two common use cases I've found:

  1. When you're implementing an interface that allows asynchronous callers, but your implementation is synchronous.
  2. When you're stubbing/mocking asynchronous code for testing.