Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async vs non-async methods in a new library [closed]

In .NET 4.5, there are many methods that now come in async and non-async pairs, such as Flush() and FlushAsync(). Ideally I/O interactions would always be asynchronous where possible (you can always block with .Wait() if you really want to), but the non-async (blocking) versions obviously need to remain due to backwards compatibility.

When rolling out a completely new library that has no backwards compatibility restrictions, is there any reason why one would include the non-async methods?

like image 594
Gigi Avatar asked Sep 22 '14 06:09

Gigi


People also ask

Should I use async or not?

Asynchronous loops are necessary when there is a large number of iterations involved or when the operations within the loop are complex. But for simple tasks like iterating through a small array, there is no reason to overcomplicate things by using a complex recursive function.

What happens if async method is called without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Does async methods create a new thread?

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

Does async improve performance?

Using asynchronous code does not give an increased performance on a development machine. The reason is that there is not enough load to see the overall benefit. But for a production environment, it can process more requests.


1 Answers

Async methods usually have a cost associated with them as there is a state machine generated by the compiler which results in quite a bit of extra code. If you are not using the async methods they won't be jitted so you avoid that cost.

If you use the async version and simply call Wait() you are risking a deadlock and also you would incur an extra context switch once the async operation completes. So overall the result would perform slightly worse.

Also any exceptions you get will now be wrapped in an AggregatedException so there will be extra work in exception processing as well. Have a look at Async Performance: Understanding the Costs of Async and Await

like image 143
NeddySpaghetti Avatar answered Nov 07 '22 02:11

NeddySpaghetti