Home > front end >  What is difference between Task.FromResult and Task.CompletedTask?
What is difference between Task.FromResult and Task.CompletedTask?

Time:06-07

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

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

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


    

CodePudding user response:

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

CodePudding user response:

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.

  • Related