What is difference between Task.FromResult and Task.CompletedTask?
public Task Test1()
{
return Task.CompletedTask;
}
public Task Test2()
{
return Task.FromResult(0);
}
>Solution :
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.