2

What's the practical difference (if any) between these two methods?

    public static Task DoSomething()
    {
        return FooAsync();
    }

    public static async Task DoSomethingAsync()
    {
        await FooAsync();
    }
Shaul Behr
  • 36,951
  • 69
  • 249
  • 387
  • 2
    [Here is a good place to start...](https://msdn.microsoft.com/en-us/library/mt674882.aspx) – Zohar Peled Jan 03 '17 at 09:43
  • Whoever marked this as duplicate is wrong. OP is not asking whether to use one or the other, but rather what the difference is and the answer is a lot different from the answers in the linked question. – Bauss Jan 03 '17 at 09:52

3 Answers3

2

The practical difference in terms of using these is: nothing. Both are 'awaitable'.

There will be a small difference in the generated code, the async version will be turned into a state-machne. Not really something to worry about.

Since these methods do nothing else it's hard to prefer one over the other. The first (simplest) one will do.

H H
  • 263,252
  • 30
  • 330
  • 514
0

await will actually wait for the task to finish and return the result. When you return a task its returning a handle to the Task which will complete in future, hence you await on the task to get the results.

Chirdeep Tomar
  • 4,281
  • 8
  • 37
  • 66
  • Methods that use `await` return a Task anyway, so you *still* have to await for them – Panagiotis Kanavos Jan 03 '17 at 09:46
  • `await` does _not wait_ for `FooAsync()` to finish, it returns to the caller immediatly (if the `Task` returned by `FooAsync()` is not yet completed). And when that inner task gets completed, `DoSomethingAsync()` will eventually resume after the `await`... so there is no difference as there is nothing to resume... it's just compiler overhead. – René Vogt Jan 03 '17 at 09:46
  • Yes I agree it relinquishes control but it await will make it wait for the results. I didn't mean await will make it synchronous, making it a blocking call. – Chirdeep Tomar Jan 03 '17 at 09:51
0

The DoSomething() will be executed when asked by the caller. So it will be executed when you will do await DoSomething();. But you can store the task in a variable and execute it later :

var task = DoSomething();
// Do stuff
await task();

With DoSomethingAsync, it will be executed when called. Because it's asynchronous.

Floc
  • 668
  • 8
  • 16
  • Yes, one is async. But both have 'deferred execution' , there is absolutely no difference in when or how FooAsync() is called. – H H Jan 03 '17 at 09:51