Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I omit async / await if possible?

Tags:

c#

async-ctp

I have a method which takes long to run: it calls the DB and makes certain calculations synchronously:

public static MyResult MyMethod(int param1, int param2)
{
    // run a DB query, wait for result, make calculations...
    ...
}

I want to write a wrapper for it, to be able to use it from my WinForms UI with 'await' keyword. To do this, I create another method, MyResultAsync. I have a choice, how exactly to write it:

// option 1
public async static Task<MyResult> MyResultAsync(int param1, int param2)
{
    return await TaskEx.Run(() => MyMethod(param1, param2));
}

// option 2
public static Task<MyResult> MyResultAsync(int param1, int param2)
{
    return TaskEx.Run(() => MyMethod(param1, param2));
}

So, which option is preferable and why? As you can see, the difference is just in presence/absence of 'async' and 'await' keywords.

Thank you!

like image 216
Pavel Zhur Avatar asked Nov 22 '11 05:11

Pavel Zhur


2 Answers

Use the second option.

Your first option creates a Task<MyResult>, and then creates another Task<MyResult> to wrap it. The wrapping doesn't add any value, just overhead.

Stephen Toub has a great video from BUILD called The Zen of Async: Best Practices for Best Performance, which covers the async/await overhead and alternatives.

like image 54
Stephen Cleary Avatar answered Nov 14 '22 16:11

Stephen Cleary


Its all about how async actually works. If you read http://msdn.microsoft.com/en-us/magazine/hh456402.aspx and in particular: http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229662.aspx you'll find that the async keyword makes the compiler build a statemachine within your code. This is overhead and for performance sake, will perform worse since it's absolutely not required in the code given.

As for readability: I should use async only where it really can make a difference. async for me means that a certain method finishes in multiple steps in an async manner. When you define a simple proxy method like the above, you dont want to complicate the syntax any further.

like image 38
Polity Avatar answered Nov 14 '22 17:11

Polity