rudimenter
rudimenter

Reputation: 3460

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.

Upvotes: 13

Views: 3910

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457332

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.

Upvotes: 11

Related Questions