C# – Await and Async

Leave a comment

In a previous post, we looked at the Task Parallel Library. In this post we will look at Await and Async in C#.

In our previous example, when clicking a button we will wait 5 seconds, then display a message to the user, and without locking up the UI.

We will tell our function that it will run asynchronously using the async keyword, and use await to tell the compiler to wait on this call before moving to the next call.

The new code looks like below:

Compare this to the old code:

Running this, if we use the debugger, we will see task1 will run, wait 5 seconds, complete and then move on to the MessageBox.

This pattern is basically running asynchronous code in a “synchronous” way. Note JavaScript has a similar pattern.

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

Leave a Reply

Your email address will not be published. Required fields are marked *