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.
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL