lysergic-acid
lysergic-acid

Reputation: 20050

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

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.

Upvotes: 264

Views: 157596

Answers (7)

Alborz
Alborz

Reputation: 6903

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: Create pre-computed tasks.

Upvotes: 7

goughy000
goughy000

Reputation: 678

From msft.com Create pre-computed tasks with Task.FromResult:

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.

Upvotes: 27

Task.Run() creates an lambda thread, no async is required and returns a type object. In my example, I have multiple tasks running simulatenously awaiting their completion. Once all the tasks have completed, I can cycle through their results. Task.FromResult is used to push a task result not generated by Task.Run()

The Task.FromResult pushs a type object in this case RecordStruct class in Result class. I created to tasks calling the function getData. The Task.WaitAll processes each of the task and push the results into an array of result object of type RecordStruct. I then access the attribute element of the RecordStruct Class as a result

    public class RecordStruct
    {
        public RecordStruct(string _element) {
            element = _element;
        }
        public string element { get;set; }
    }

public class TaskCustom
    {
        public Task<RecordStruct> getData(string phrase)
        {
            if (phrase == "hello boise")
            {
                return Task.FromResult(new RecordStruct("Boise is a great place to live"));
            }

            return Task.Run(() =>
            {
                return new RecordStruct(phrase);
            });
        }
    } 

[Fact]
        public async Task TestFactory()
        {
            TaskCustom obj = new TaskCustom();
            List<Task<RecordStruct>> tasks = new List<Task<RecordStruct>>();
            tasks.Add(obj.getData("hello world"));
            tasks.Add(obj.getData("hello boise"));

            Task.WaitAll(tasks.ToArray());

            for(int ctr = 0; ctr < tasks.Count; ctr++) {
                if (tasks[ctr].Status == TaskStatus.Faulted)
                    output.WriteLine(" Task fault occurred");
                else
                {
                    output.WriteLine("test sent {0}",
                                      tasks[ctr].Result.element);
                    Assert.True(true);
                }
            }
        }

Upvotes: -2

Viking
Viking

Reputation: 465

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.

Upvotes: -2

Matt Smith
Matt Smith

Reputation: 17444

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

Upvotes: 67

Edminsson
Edminsson

Reputation: 2506

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.

Upvotes: 49

Stephen Cleary
Stephen Cleary

Reputation: 456537

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.

Upvotes: 367

Related Questions