Should I omit async / await if possible?
Asked Answered
G

2

5

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!

Gladdy answered 22/11, 2011 at 5:29 Comment(0)
A
8

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.

Allanson answered 22/11, 2011 at 16:43 Comment(2)
There is one pitfall though, returning the task inside a using block may cause the Dispose method to be called before the task has finishedRhody
@PabloRetyk: Yes, there are a few pitfalls explored here.Allanson
S
4

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.

Steven answered 22/11, 2011 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.