Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 7129 |  Welcome, Guest!   Register  Login
Home > Articles > C# > How to perform Asynchronous Processing in .Net

How to perform Asynchronous Processing in .Net

1 vote(s)
Rating: 4 out of 5
Article posted by Hmanjarawala on 11/24/2011 | Views: 3974 | Category: C# | Level: Intermediate | Points: 250 red flag

Advertisements

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

Download


 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.

Advertisements

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:7 year(s)
Home page:http://himanshumbri.blogspot.com
Member since:Saturday, July 30, 2011
Level:Bronze
Status: [Member]
Biography: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.
 Responses
Posted by: Nerdanalysis | Posted on: 25 Nov 2011 11:25:19 AM | Points: 25

Although i am more into web but this article is easy to understand. Thanks Himanshu....

Posted by: Arefin | Posted on: 27 Nov 2011 10:45:22 PM | Points: 25

I faced this kind of problem about 6 month ago. You solution is good.

>> Write Response - Respond to this post and get points
Related Posts

The article gives an overview of Server Controls in ASP.NET.

In this article we shall see how to manage threads in C#.

WeakReference comes very handy when working with Large objects. In this application, I have demonstrated how you could easily use this class to improve the performance of your application.

We will see The C# threading model.

We upload images to Amazon s3 because it serve the uploaded files more efficient content delivery network of Amazon.This article describes on how to upload image file to Amazon s3.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 6/20/2013 12:58:07 AM