Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is the use of Task FromResult?

The FromResult method returns a finished Task<TResult> object that holds the provided value as its Result property. This method is useful when you perform an asynchronous operation that returns a Task<TResult> object, and the result of that Task<TResult> object is already computed.

What is the use of Task WhenAll?

WhenAll(Task[])Creates a task that will complete when all of the Task objects in an array have completed.

What is Task in threading?

The Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel. The task can return a result.

What is Task CompletedTask?

Task. CompletedTask property is important when you need to give a caller a dummy Task (that doesn't return a value/result) that's already completed. This might be necessary to fulfill an "interface" contract or testing purposes. Task. FromResult(data) also returns a dummy Task, but this time with data or a result.


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.

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 it when you want to create an awaitable method without using the async keyword. I found this example:

public class TextResult : IHttpActionResult
{
    string _value;
    HttpRequestMessage _request;

    public TextResult(string value, HttpRequestMessage request)
    {
        _value = value;
        _request = request;
    }
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage()
        {
            Content = new StringContent(_value),
            RequestMessage = _request
        };
        return Task.FromResult(response);
    }
}

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.


From MSDN:

This method is useful when you perform an asynchronous operation that returns a Task object, and the result of that Task object is already computed.

http://msdn.microsoft.com/en-us/library/hh228607.aspx