4

Hi I have a small question with async/await on webapi. Is there a difference between these two usages and which one is considered the correct one? After reading SimilarQuestion on SO I guess Variant 1 is better because of less overhead but I need to be sure, therefore I ask again;)

Variant 1:

public Task<string> Get(){
    return Bar();
}

variant 2:

public async Task<string> Get(){
    return await Bar();
}

Methods:

public async Task<string> Foo(){
    await Task.Delay(5000);
    return "Done";
}

public Task Bar(){
    return Foo();
}

Thanks for hints

Community
  • 1
  • 1
xartal
  • 427
  • 6
  • 18

1 Answers1

1

Variant 2 is not possible because you can not do

public async Task<string> Get(){
    return await Bar();
}

public Task Bar(){
    return Foo();
}

await only works for async and Task Bar() is not async... its just Task.

Look at Can I not await for async Task without making it async void? It says

The correct way to handle this is to await the method, and make the calling method async Task. This will have a cascading effect as async travels up through your code.

Having said that, you are left with variant 1. This is a good option for most cases. If you feel async await will have a negative impact on performance, you are probably making the wrong methods async. But again, you need to calibrate that. There cant be a common answer for this that address all methods.

Also see :

  1. the-overhead-of-asyncawait-in-net-4.5
  2. Behind the .NET 4.5 Async Scene: The performance impact of Asynchronous programming in C#
Community
  • 1
  • 1
Bilal Fazlani
  • 6,727
  • 9
  • 44
  • 90
  • 1
    Thanks for the answer! Should have testet it before i ask. But now i have the following question: is there a difference between those variants: async Task Get(){return await Foo();} or Task Get(){return Foo();}? – xartal Apr 30 '15 at 10:56
  • Yes. async adds a performance overhead. But why would you use a Task without async ? – Bilal Fazlani Apr 30 '15 at 10:58
  • okay, perfect. it is not production code I just try to understand how it works. thank you! – xartal Apr 30 '15 at 11:00
  • If you have used async for the top method, it's safe to use it in all subsequent child methods as the async overheard will remain same. – Bilal Fazlani Apr 30 '15 at 11:00
  • Ok. And for asp.net WebAPI it makes no difference if i declare a Method as "async Task Get()" and await TaskX inside of Get or if i declare it as "Task Get()" and return the TaskX directly, right? – xartal Apr 30 '15 at 11:05
  • that's correct. Most of the overhead is added by the first async. That's why you should chain it until you reach the last primitive async method. – Bilal Fazlani Apr 30 '15 at 11:13