Waiting for Task.CompletedTask for what?

I created a UWP application with Windows Template Studio , which was introduced at Build2017.

The class below is part of the 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 for the code await Task.CompletedTask;here? In fact, he does not have a recipient of results Task.

+6
source share
1 answer

Perhaps it is there to simplify the next step for implementing asynchronous code calls without having to change the signature, thereby preventing the need for refactoring the calling code.

- async

return Task.FromResult<IEnumerable<SampleModel>>(data); 

, - , , async.

, , , await Task.Completed - await FetchDataFromDatabaseAsync();. async , .

, :

public class SampleModelService
{
    public Task<IEnumerable<SampleModel>> GetDataAsync()
    {
        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 Task.FromResult<IEnumerable<SampleModel>>(data); 
     }
}

( ), . ( , )

, , - async , , Task.

+9

All Articles