Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between those two methods returning Task [duplicate]

Tags:

c#

async-await

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?

like image 808
Francesco Bonizzi Avatar asked Sep 27 '26 09:09

Francesco Bonizzi


1 Answers

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.

like image 123
Lasse V. Karlsen Avatar answered Sep 29 '26 22:09

Lasse V. Karlsen



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!