Should I ignore async / expected if possible?

I have a method that lasts a long time: it calls the database and performs 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 so that I can use it from my WinForms interface with the keyword 'wait'. To do this, I create another method, MyResultAsync. I have a choice of how 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 only difference is the presence / absence of the keywords "async" and "wait".

Thanks!

+4
source share
2 answers

Use the second option.

Your first option creates a Task<MyResult> , and then creates another Task<MyResult> to transfer it. The wrapper does not add any value, just the overhead.

Stephen Tuub has an excellent BUILD video called Zen Async: Best Practices for Better Performance , which covers async / await overhead and alternatives.

+6
source

All about how async 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 will find that the async keyword forces the compiler to build statemachine inside your code. This is overhead and for the sake of performance, it will work worse, since it is absolutely not required in the above code.

Regarding readability: I should use async only where it really can make a difference. async for me means that a particular method ends in several steps in an asynchronous manner. When you define a simple proxy method like the one above, you no longer want to complicate the syntax.

+4
source

Source: https://habr.com/ru/post/1382428/


All Articles