Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should i use async/await and when not?

Should i use async/await from now on (c# 5) everytime when i don't require the outcome of an method immediatelly (Task<>) or i have to fire a one-off method (void)?

Should i use it in all the cases when i used the Task class in C# 4 and pushed work to the Backgroud threads?

Should i use it only in cases when i used asynchronous .Net Framework Methods?

Confused.

I am basically looking for a simple explanation in which cases i should use await/async and when not.

like image 763
rudimenter Avatar asked Oct 01 '12 14:10

rudimenter


1 Answers

async / await may be used when you have asynchronous operations. Many operations are naturally asynchronous (such as I/O); I recommend async for all of those. Other operations are naturally synchronous (such as computation); I recommend using synchronous methods for those.

You can use Task.Run with async for background work if you need to run synchronous code asynchronously. I explain on my blog why this is better than BackgroundWorker and asynchronous delegates.

You can also use async to replace other forms of asynchronous processing, e.g., the IAsyncResult style.

You should use async in any situation where you have an asynchronous operation.

like image 127
Stephen Cleary Avatar answered Oct 29 '22 15:10

Stephen Cleary