2 Ways to Implement Asynchronous Technique in C#

A few days ago in our organization we were trying to implement asynchronous programming (obviously in C# with Visual Studio 2010). First of all Visual Studio 2010 targets the .NET framework 4.0 and asynchronous programming is the concept of C# 5.0 that demands .NET framework 4.5 to compile and run.

The problem starts here. We are using Visual Studio 2010. The highest version of the .NET Framework that it supports is 4.0 and we are very much interested in implementing the asynchronous style in applications. Our project and source version control and other related software are licensed for Visual Studio 2010. So, what is the solution? We need to use Visual Studio 2012 (at least) to use .NET framework 4.5 and then we are able to use the features of C# 5.0. (Ok, you are suggesting use of the async CPT in VS2010). Believe me, I have tried the async CPT in VS2010 but it is not fully supported. (Let's not create a debate with this topic, proceed with our explanation). In this article we will see how to implement an asynchronous style in C# applications. (Yes, even in .NET 4.0).

Implement by delegate

This will be our first approach to implement the asynchronous style. Let's implement a small example to understand it.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Asynchronious

{

    class Program

    {

 

        delegate void delHugeTask();

        static void Main(string[] args)

        {

 

            //Create object to delegate

            delHugeTask objHugeTask = new delHugeTask(Program.HugeTask);

 

            //Call the delegate asynchoniously

            objHugeTask.BeginInvoke(new AsyncCallback(Program.callbackFunction),objHugeTask);

 

            Console.WriteLine("Main Task finished. Waiting for Huge Task");

            Console.ReadLine();

 

        }

 

        //Callback function to return result from Huge Task function

        public static void callbackFunction(IAsyncResult obj)

        {

        }

        public static void HugeTask()

        {

            System.Threading.Thread.Sleep(5000);

            Console.WriteLine("Huge Task Finished");

        }

    }

}

This example is quite simple to understand. We have created one function called "HugeTask()" that has only two lines of code but huge in nature. (Ha.. Ha...,Yah we are making a delay intentionally.) We will now call this function asynchronously. In other words, our program will not wait for the function.

When we invoke any method using a delegate we basically use an Invoke method to call the function, but it's synchronous in nature. At first the calling function will execute and after that control will get to the calling position (from where invoke() has used). In this example however we are interested in calling HugeTask() asynchronously. In other words the program will call HugeTask() but control will not wait for it to finish. It will proceed to execute the next line.

Here we have used the BeginInvoke() method to do this trick. Here is the sample output.

Csharp1.jpg

We see that the first Main() function is finishing it's task before the "HugeTask()" function. In other words, it's calling the "HugeTask()" function but not waiting for it finish it.

Using C# 5.0, async and await keyword

This is the proper way to implement the asynchronous style in C# applications. Let's update your Visual Studio and try it. I hope most of you are already aware of this feature and have also implemented it (at least in test). Have a look at the following code.
 

using System;

using System.ComponentModel;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        public static Task LongProcess()

        {

            return Task.Run(() =>

            {

                System.Threading.Thread.Sleep(5000);

            });

        }

 

        public async void CallProcess()

        {

            await LongProcess();

            this.listBox1.Items.Add("Long Process finish");

        }

        private void Form1_Load(object sender, EventArgs e)

        {

 

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            this.label1.Text = "Return Void";

            CallProcess();

            this.listBox1.Items.Add("Program Finish");

        }

    }

}


This is one Windows application and we have implemented an asynchronous nature in it. The "LongProcess()" will run for 5 seconds and at the end of execution it will return Task. (If you are not familiar with Task, I suggest you refer the MSDN for it or wait a few days, very soon I will start a series on the topic of asynchronous programming in C#) . Let's get to our explanation. "CallProcess()" will call "LongProcess()" with an asynchronous style. In other words, "CallProcess()" will call "LongProcess()" but it will not wait for "LongProcess()" to finish. Program control will return to the Main calling location. (Here it is a button's click event.)

Here is sample output.

Csharp2.jpg

Conclusion

In this article we have implemented an asynchronous style in two ways. If you are brand new to the concept of asynchronous then I suggest you go through the basic idea of it. Follow my next series to learn asynchronous concepts in C# 5.