-1

I'm having a bit of a sanity check that needs resolving:

Is there a difference between

Task.Run(async () => await dothingAsync());

and

Task.Run(dothingAsync);

Edit (signature of dothingasync)

private Task dothingAsync();

Or

private async Task dothingAsync();
maxfridbe
  • 5,872
  • 10
  • 58
  • 80
  • What's the type/signature of `dothingAsync(a,b)`? – Paulo Morgado Aug 22 '19 at 22:54
  • 5
    People ask this question all the time -- there are many duplicates -- and it always mystifies me. Let's clarify your question by asking you a question. Here are two workflows: (1) you write a to-do list that says 'make me a sandwich' and hand it to a friend, who starts making you a sandwich. (2) you write a to-do list that says "make a to-do list that says to make me a sandwich, and then do what is on that list", and you hand it to a friend, and they write a to-do list that says to make you a sandwich, and then they make you a sandwich". **What is the difference between those workflows?** – Eric Lippert Aug 22 '19 at 23:04
  • 1
    Both workflows get you a sandwich. Both workflows have the sandwich made by someone other than you. So, are they the same, because they have the same outcomes? Or are they different, because one is needlessly more complicated? Without understanding what you mean by "the same" and "different" it is impossible to answer your question with any kind of confidence. – Eric Lippert Aug 22 '19 at 23:05
  • 1
    The first example will create 2 `IAsyncStateMachines` instead of 1. Also note if you do this on a method signature that takes an action, you will create an async void – TheGeneral Aug 22 '19 at 23:10

1 Answers1

2

Here's a blog post on the subject that dives into more detail. There's also this Stack Overflow post that is very similar except it deals with methods and your question deals with lambdas (which are converted by the compiler into methods).

In summary, the two approaches are almost equivalent. Using the keywords does introduce a state machine. In this case - since the lambda just calls a single method and returns its result - eliding the keywords is appropriate. If you do include async and await, it would just add a bit of overhead for no benefit.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810