Mahdi Anjam
Mahdi Anjam

Reputation: 298

What is difference between Task.FromResult and Task.CompletedTask?

What is difference between Task.FromResult and Task.CompletedTask?

public Task Test1()
{
    return Task.CompletedTask;
}

public Task Test2()
{
    return Task.FromResult(0);
}

Upvotes: 4

Views: 2519

Answers (2)

Hans Kesting
Hans Kesting

Reputation: 39283

Your Task.FromResult(0) really returns a Task<int>, not (just) a plain Task.

So this would compile fine

 public Task<int> Test2()
 {
     return Task.FromResult(0);
 }

You couldn't use a Task.CompletedTask here.


Late EDIT
Another difference is that Task.CompletedTask is a cached value (read: no new allocation needed), while Task.FromResult(..) may need to create a new Task instance (although it tries to return a cached instance if possible, such as for default values).

Upvotes: 6

Zoran Horvat
Zoran Horvat

Reputation: 11301

The CompletedTask has no result field, and no generic type parameter for that matter. You can use it to just skip taking system resources to do a job.

The FromResult variant returns a generic Task, with the argument's type being the generic type parameter. You can use this variant to avoid wasting resources to just return a value, in contexts where caller expects asynchronous behavior and hence requests a Task back.

Please note that generic Task<T> is deriving from non-generic Task, and hence both methods are equally valid in contexts where the caller makes a fire-and-forget call, or just doesn't care to read the result.

Upvotes: 2

Related Questions