3

What's the Semantic difference between those two methods?

    public Task DoSomething()
    {
        return Task.Run(() => MyFunction());
    }

    public async Task DoSomethingAsync()
    {
        await Task.Run(() => MyFunction());
    }

Is there something I should think to choose between one or the other?

Francesco Bonizzi
  • 5,142
  • 6
  • 49
  • 88

1 Answers1

7

The actual difference is this:

  1. The first method will call Task.Run and return the resulting task
  2. The second method will be transformed into an async state machine that will call Task.Run, then queue up a continuation that when this task completes, will continue executing your method

In terms of "which one should I choose", here's the general guideline I use:

If all your method is going to do in relation to tasks is to return them then do not use async/await
If, instead, you need to "wait for" a task to complete, then do more stuff, then use async/await.

I am sure there are exceptions to this but I have yet to find any.

So of those two methods, pick the first.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825