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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With