Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Brief explanation of Async/Await in .Net 4.5

How does Asynchronous tasks (Async/Await) work in .Net 4.5?

Some sample code:

private async Task<bool> TestFunction() {   var x = await DoesSomethingExists();   var y = await DoesSomethingElseExists();   return y; } 

Does the second await statement get executed right away or after the first await returns?

like image 999
Mayank Avatar asked Oct 26 '12 06:10

Mayank


People also ask

How do you explain async await?

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

What is async and await in .NET core?

The async and await keywordsAn asynchronous method is one that is marked with the async keyword in the method signature. It can contain one or more await statements. It should be noted that await is a unary operator — the operand to await is the name of the method that needs to be awaited.

What is async await in asp net?

The await keyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code. The async keyword represents a hint that you can use to mark methods as task-based asynchronous methods.

What does await do in async C#?

The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes.


2 Answers

await pauses the method until the operation completes. So the second await would get executed after the first await returns.

For more information, see my async / await intro or the official FAQ.

like image 105
Stephen Cleary Avatar answered Oct 06 '22 02:10

Stephen Cleary


It executes after the first await returns. If this thing confuses you, try to play around with breakpoints - they are fully supported by the new async pattern.

Imagine it would look like this:

var x = await GetSomeObjectInstance(); var y = await GetSomeObjectInstance2(x); 

There probably would occur a NullReferenceException somewhere, so the first await has to return first. Otherwise, x would be null/undefined or whatever.

like image 38
nikeee Avatar answered Oct 06 '22 02:10

nikeee