Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing `Func<Task>` to a method - any differences between calling func vs. lambda vs. async/await lambda?

Tags:

c#

async-await

Let's consider methods:

public static void FireAsyncAndForget(Func<Task> func)
{
    JoinableTaskFactory.RunAsync(func).FileAndForget();
}

async Task DoAsync()
{
    await SomeOtherMethodAsync();
}

Is there any difference in terms of how the code is executed between the 3 examples below?

  1. FireAsyncAndForget(DoAsync);
  2. FireAsyncAndForget(() => DoAsync());
  3. FireAsyncAndForget(async () => await DoAsync());
like image 902
Grzegorz Smulko Avatar asked Jul 17 '26 18:07

Grzegorz Smulko


1 Answers

Unless I'm mistaken, all three of these will seemingly execute identically, though there is a subtle difference.

Option 1 will execute DoAsync directly, while the other two are calling a function that itself calls DoAsync. This will create an extra entry on your stack. Same logic applies to option 3 compared to 2, there is an extra await call and so (unless the compiler optimizes it away) I would expect it to generate an extra state.

Seeing a notable run time difference between these, though, I would expect to be in the realm of micro-optimizations.

like image 194
Shaun Hamman Avatar answered Jul 19 '26 07:07

Shaun Hamman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!