In C#, there is a feature called Task Parallel Library that was introduced in .NET 4.0 and is useful for handling asynchronous calls.
Let’s create a new C# Windows Forms application. Windows forms apps are good to demo this as they can get locked up with long running synchronous calls:
Add a button to the Win Form:
Let’s say we want to simulate some long running code. We will use Thread.Sleep() to call a function that sleeps for 5 seconds:
Running this, and clicking on Do Something, we will see a 5 second wait before the message appears. During that wait, we will not be able to move the form, as the UI is locked processing the sleep:
Let’s use the Task Parallel Library to run our code. We will add Task.Run, which accepts an action as a parameter:
This action has no inputs, so we will use (), then our lambda operator =>, then what we would like to do:
Now, when we run and click on Do Something, we will see the UI is not locked – we can move the window around. The code will then complete:
Now, it would be nice to add additional code when our task has been completed. In order to do this, we can use the “continuation”, meaning when our task is completed, do something else.
We will assign our task to a variable, task1. We will then add task1.ContinueWith, that will run when task1 has completed. We will return in task1 a result of our message, and display it in the ContinueWith:
Running this, as before, when clicking the button, the UI is not locked and the code runs asynchronously. As you can see, at this point, we could potentially return errors from our first task asynchronous call, and then determine whether to “ContinueWith” the rest of the code.
Now, what if we want to tell our ContinueWith that an error has occurred? We can do this using IsFaulted:
When we run this, the code will go into IsFaulted and display the error message:
Another way to do “ContinueWith” is to use “ConfigureAwait”. If you need to use the UI thread (as opposed to a separate thread), it will use this:
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