What is the purpose of “return await” in C#?

前端 未结 7 2228
半阙折子戏
半阙折子戏 2020-11-21 07:18

Is there any scenario where writing method like this:

public async Task DoSomethingAsync()
{
    // Some synchronous code          


        
7条回答
  •  情深已故
    2020-11-21 07:46

    Another case you may need to await the result is this one:

    async Task GetIFooAsync()
    {
        return await GetFooAsync();
    }
    
    async Task GetFooAsync()
    {
        var foo = await CreateFooAsync();
        await foo.InitializeAsync();
        return foo;
    }
    

    In this case, GetIFooAsync() must await the result of GetFooAsync because the type of T is different between the two methods and Task is not directly assignable to Task. But if you await the result, it just becomes Foo which is directly assignable to IFoo. Then the async method just repackages the result inside Task and away you go.

提交回复
热议问题