await Task.CompletedTask for what?

Viewed 27782

I created UWP app with Windows Template Studio that introduced at Build2017.

Below class is a part of generated code from it.

public class SampleModelService
{
    public async Task<IEnumerable<SampleModel>> GetDataAsync()
    {
        await Task.CompletedTask; // <-- what is this for?
        var data = new List<SampleModel>();

        data.Add(new SampleModel
        {
            Title = "Lorem ipsum dolor sit 1",
            Description = "Lorem ipsum dolor sit amet",
            Symbol = Symbol.Globe
        });

        data.Add(new SampleModel
        {
            Title = "Lorem ipsum dolor sit 2",
            Description = "Lorem ipsum dolor sit amet",
            Symbol = Symbol.MusicInfo
        });
        return data;
    }
}

My question is, what is the purpose and reason of await Task.CompletedTask; code in here? It actually does not have Task result receiver from it.

2 Answers

await Task.CompletedTask makes it easier to implement this method as the first answer said, Since this implementation isn't time-consuming, and thus "await Task.CompletedTask;" or "return Task.FromResult(data);" both will run synchronously. You can use those two pattern mentioned above, but this method is designed to be an asynchronous method, so when your implementation is time-consuming but don't have any async code, use Task.Run to create a task.

Related