How to perform Asynchronous Processing in .Net

Hmanjarawala
Posted by in C# category on for Intermediate level | Points: 250 | Views : 6332 red flag
Rating: 4 out of 5  
 1 vote(s)

This article demonstrate how to perform asychronous task processing in .Net using events and delegates


 Download source code for How to perform Asynchronous Processing in .Net

Introduction

                        Hi, today we will demonstrate asynchronous processing using delegates and events. One might think what the need of doing work  asynchronously in windows environment. Yes, it is required and thought following  sample example we will substantiate this.

The Program

                        In this program we will develop a class will have certain events and delegates to handle those events. Our class will have a function to perform task and continuously changes the status through raising events.

Start Visual Studio 2008 IDE and Select Create New Project. Select C#->Windows Application Template from Create Project Explorer and Give a name “MyApplication”

Now add new class named Task in project “MyApplication”. Code for class Task is shown below

public class Task

    {

        public delegate void UpdateStatusEventHandler(string text, int total, int current);

        public delegate void UpdateTextEventHandler(string text);

        public delegate void UpdateProgressBarEventHandler(int total, int value);

 

        public event UpdateStatusEventHandler UpdateStatus;

        public event UpdateTextEventHandler UpdateText;

        public event UpdateProgressBarEventHandler UpdateProgressBar;

 

        public void PerformTask(int totalTask)

        {

            for (int i = 0; i < totalTask; i++)

            {

                UpdateText("Task Started.....");

                UpdateStatus("Task Performing", totalTask, i + 1);

                System.Threading.Thread.Sleep(50);

                UpdateText("Task Completed.....");

                System.Threading.Thread.Sleep(50);

                UpdateProgressBar(totalTask, i);

            }

        }

    }

                        As shown in code, we defined 3 events for updating status, text and progress bar value as per task perform. For handling these events we define 3 delegates. As we all knows delegate works asynchronously, so whenever we raise these events, they will execute asynchronously.

This event is handled from Windows Form. Code to handle these events are as follows.

            Task task = new Task();

            task.UpdateProgressBar += new Task.UpdateProgressBarEventHandler(task_UpdateProgressBar);

            task.UpdateStatus += new Task.UpdateStatusEventHandler(task_UpdateStatus);

            task.UpdateText += new Task.UpdateTextEventHandler(task_UpdateText);

In order to handle these events, we’ve to register them first. To register them, first create instance of class which owns those events. As you can see delegates which we defined in that class are working as event handler and each event handler has reference of a function having code for handling this events.

        private void task_UpdateStatus(string text, int total, int current)

        {

            eUpdateStatus(lblStatus, text, total, current);

        }

 

        private void task_UpdateText(string text)

        {

            eUpdateText(lblText, text);

        }

 

        private void task_UpdateProgressBar(int total, int value)

        {

            eUpdateProgressBar(pbTask, total, value);

        }

Now let us see how to update windows control state asynchronously. For that you have to define delegates. As we knows delegates are special typed class which can point function having same signature. We’ll define delegates and functions that work asynchronouly for us.

        private delegate void delUpdateStatus(Label lbl, string text, int total, int current);       

        private void mUpdateStatus(Label lbl, string text, int total, int current)

        {

            if (lbl.InvokeRequired)

            {

                lbl.BeginInvoke(new delUpdateStatus(mUpdateStatus1), lbl, text, total, current);

            }

        }

 

        private void mUpdateStatus1(Label lbl, string text, int total, int current)

        {

            lbl.Text = string.Format("{0}/{1}\n {2}", current, total, text);

            lbl.Update();

            lbl.Parent.Update();

            this.Update();

        }

As we shown above, we defined delegate and its function for updating label status. Here you notice "BeginInvoke" method which executes asynchronously for updating control status

Hope this article has helped to understand the asynchronous task processing and where we can utilize that.

Page copy protected against web site content infringement by Copyscape

About the Author

Hmanjarawala
Full Name: Himanshu Manjarawala
Member Level: Bronze
Member Status: Member
Member Since: 7/30/2011 7:42:18 AM
Country: India
Himanshu Manjarawala Sr. Software Engineer@AutomationAnywhere http://fieredotnet.wordpress.com/
http://himanshumbri.blogspot.com
I am Himanshu Manjarawala, Graduate in Computer Science and MCA From Veer Narmad South Gujarat University, Surat Gujarat India. Currently working as Sr. Software Developer in Automation Anywhere.

Login to vote for this post.

Comments or Responses

Posted by: Nerdanalysis on: 11/25/2011 | Points: 25
Although i am more into web but this article is easy to understand. Thanks Himanshu....
Posted by: Arefin on: 11/27/2011 | Points: 25
I faced this kind of problem about 6 month ago. You solution is good.

Login to post response

Comment using Facebook(Author doesn't get notification)