Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between the following Func<Task<T>> async delegate approaches?

Tags:

c#

async-await

If I have the following method:

public async Task<T> DoSomethingAsync<T>(Func<Task<T>> action)
{
   // bunch of async code..then "await action()"
}

What is the difference between the following two usages:

public async Task MethodOneAsync()
{
   return await DoSomethingAsync(async () => await SomeActionAsync());
}

public async Task MethodTwoAsync()
{
   return await DoSomethingAsync(() => SomeActionAsync());
}

Both compile, both work and there are no C# warnings.

What's the difference (if any)? Will both methods run true async if awaited by the caller?

like image 417
RPM1984 Avatar asked Oct 14 '16 05:10

RPM1984


1 Answers

There is no functional difference between the two. The only difference is if the Task from SomeActionAsync is returned directly or if it is awaited. Stephen Cleary has a good blog post about this, and recommends the second aproach for this trivial case.

The reason why the first approach is available is that you could have a non-trivial lambda expression like this:

public async Task MethodOneAsync()
{
    return await DoSomethingAsync(async () => {
        var i = _isItSunday ? 42 : 11;
        var someResult = await SomeActionAsync(i);
        return await AnotherActionAsync(someResult*i);
    });
}

So the difference is the same as the difference between a method whith this signature public async Task<int> MyMethod and this one public Task<int> MyMethod

like image 85
Joakim M. H. Avatar answered Oct 24 '22 07:10

Joakim M. H.