SIGN UP MEMBER LOGIN:    
ARTICLE

.NET Parallel Programming with Events

Posted by Shantanu Articles | .NET 4.5 January 10, 2011
Many times the Application needs to be notified about what is happening inside a Parallel Task and also to get data (if any) from the Task in real time. For this, Events can be used with Tasks.
Reader Level:
Download Files:
 


Purpose

Many times the Application needs to be notified about what is happening inside a Parallel Task and also to get data (if any) from the Task in real time. For this, Events can be used with Tasks.

Implementation Details

Consider a Task which does the countdown starting from a user specified number. The Application wants to know each time a countdown has been done so that it can print the value to the UI. This can be done via Events.

The Class which does the Count Down is the CountDownDriver class. 


Parallel1.gif

The class exports 2 custom events.

        #region Custom Event Delegates
        public delegate void CountDown(object o, EventArgs e);
        public delegate void CountDownComplete(object o, EventArgs e);
        #endregion

        #region Custom Events
        public event CountDown OnCountDown;
        public event CountDownComplete OnCountDownComplete;
        #endregion

The OnCountDown event is fired by Parallel Task after each count down. The OnCountDownComplete event is fired after the countdown is complete.

        public void StartCountDown()
        {
            for (int i = StartNo; i >= 0; i--)
            {
                System.Threading.Thread.Sleep(1000);

                if (i == 0)
                {
                    if (OnCountDownComplete != null)
                    {
                        //Fire OnCountDownComplete event
                        OnCountDownComplete(this, new EventArgs());
                    }

                    break;
                }

                if (OnCountDown != null)
                {
                    this.CurrentCountDown = i;
                    //Fire OnCountDown event
                    OnCountDown(this, new EventArgs());
                }

            }
        }


When the Application launches the Tasks, these Events are mapped to Event Handlers in the Application.

            NoOfParallelTasks = int.Parse(tbNoOfParallelTasks.Text);

            for (int i = 0; i < NoOfParallelTasks; i++)
            {
                CountDownDriver countDown = new CountDownDriver { StartNo = int.Parse(tbStartNo.Text), TaskNo = i + 1 };

                countDown.OnCountDown += new CountDownDriver.CountDown(countDown_OnCountDown);
                countDown.OnCountDownComplete += new CountDownDriver.CountDownComplete(countDown_OnCountDownComplete);

                //Start Parallel Task
                System.Threading.Tasks.Task.Factory.StartNew(new Action(() => countDown.StartCountDown()));
            }


Thus, when these Events are fired inside the Parallel Tasks, the Application is notified and the Event Handler executes. The data from the Parallel Task is a parameter of the Event and can be accessed inside the Event Handler. In this demo, the code in the Event Handlers prints data from the Parallel Task to the UI.

        void countDown_OnCountDown(object o, EventArgs e)
        {
            lock(this)
            {
                CountDownDriver countDown = (CountDownDriver)o;

                rtbResult.Invoke(() =>
                {
                    this.rtbResult.Text = this.rtbResult.Text +
"\n"

                                               + "Countdown from parallel task "

+ countDown.TaskNo.ToString() + " : "

+ countDown.CurrentCountDown.ToString();

                });
            }
        }


Note: Invoke has to be used to acquire the UI Thread first before writing to it. I have written an Invoke() Extension Method to Control which accepts an Action (Lambda Expression) parameter as shown below :

        public static void Invoke(this Control control, System.Action action)
        {
            if (control.InvokeRequired)
            {
                control.Invoke(action);
            }
            else
            {
                action();
            }
        }

Parallel2.gif

2 Parallel Tasks are started to count down from 5 in the sample above.


Login to add your contents and source code to this article
share this article :
post comment
 

Sure Sam. BackgroundWorker can be used in most situations in a Winforms UI app. However, if real time response is required then this technique can be used in the UI too.

Posted by Shantanu Jan 13, 2011

Thank you, Shantanu. I think that since you are using a UI, readers might be confused by the article's use of the Task class and a reader might not use the BackgroundWorker class in situations that a BackgroundWorker would be appriate..

Posted by Sam Hobbs Jan 13, 2011

BackgroundWorker can be used only in a Winform UI app. Realtime response would be an issue. However, using Events with Parallel Tasks can be used in non-UI situations too eg. in Class Library projects. It is the technique I was trying to demostrate in the article not the UI update. I have used the technique in the UI as an example only. Also, the parallel task library is there in the framework with good reason.

Posted by Shantanu Jan 13, 2011

I wonder what the advantage is of using a System.Threading.Tasks.Task instead of System.ComponentModel.BackgroundWorker when the UI is frequently updated from the thread as shown in this article.

Posted by Sam Hobbs Jan 12, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Become a Sponsor