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.
From MSDN:
http://msdn.microsoft.com/en-us/library/hh228607.aspx
I would argue that you could use Task.FromResult for methods that are synchronous that take a long time to complete while you can do other independent work in your code. Id rather make those methods to call async though. But imagine the situation where you have no control over the code called and you want that implicit parallel processing.
Use it when you want to create an awaitable method without using the async keyword. I found this example:
Here you are creating your own implementation of the IHttpActionResult interface to be used in a Web Api Action. The ExecuteAsync method is expected to be asynchronous but you don't have to use the async keyword to make it asynchronous and awaitable. Since you already have the result and don't need to await anything it's better to use Task.FromResult.
One example would be a method that makes use of a cache. If the result is already computed, you can return a completed task with the value (using
Task.FromResult
). If it is not, then you go ahead and return a task representing ongoing work.Cache Example: Cache Example using Task.FromResult for Pre-computed values
Use the Task.FromResult when you want to have a asynchronous operation but sometimes the result is in hand synchronously. You can find a good sample here http://msdn.microsoft.com/en-us/library/hh228607.aspx.
There are two common use cases I've found: