Introduction
In my previous article, I talked about Asynchronous programming using the .NET framework. There we saw how to use the async and await keywords to make a function run in an asynchronous mode. We saw how to call various await-able functions provided by .NET. There are many functions provided by almost every major class of .NET which are await-able, and these mostly end with the letters Async to distinguish them from the regular functions. However, what happens when we want to change our own functions from being synchronous to be asynchronous. How can this be done? We will look at this in this article.
Changing your own functions to be await-able
We will be using a .NET framework Windows forms application to demonstrate the conversion of asynchronous function to an asynchronous function, or more simply put, we will create an asynchronous version of an existing function. So, let us begin.
We create a simple .NET framework Windows forms application and place one button (btnTest) and one label (lblValue) on it and add the code on the button click event as below:
- using System;
- using System.Threading;
- using System.Windows.Forms;
- namespace AsyncAwaitNF
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void btnTest_Click(object sender, EventArgs e)
- {
- var a = GetValue();
- lblValue.Text = a;
- }
- private string GetValue()
- {
- //Simulating a long running process
- Thread.Sleep(5000);
- return "Value is displayed now";
- }
- }
- }
Here, we see that when we click the button, we call a function called “GetValue()”. This function does some long processing, which we have simulated using the Thread.Sleep function and after that, it returns a value that is displayed on a label in the main form.
This operation is synchronous, and the form is frozen while the function runs and cannot be used.
Next, we will create an asynchronous version of this function as shown below:


Join the conversation! Your thoughts help the community grow.