Live Threads – .NET Threading and Events


Purpose

Many times the Application needs to be notified about what is happening inside a Thread. For this, Events can be used with Threads. This is what I call 'Live Threads'.

Implementation Details

Consider a Thread 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. This class exposes two custom Events viz.

        #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 thread after each count down. The OnCountDownComplete event is fired after the countdown is complete.

        public void StartCountDown()
        {
            for (int i = Count; Count >= 0; Count--)
            {
                Thread.Sleep(300);

                if (Count <= 0)
                {
                    //Fire OnCountDownComplete Event
                    if (OnCountDownComplete != null)
                    {
                        OnCountDownComplete(this, new EventArgs());
                    }

                    break;
                }

                //Fire OnCountDown Event
                if (OnCountDown != null)
                {
                    OnCountDown(Count, new EventArgs());
                }               
            }
        }

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

            CountDownDriver threadDriver = new CountDownDriver
            {
                Count = int.Parse(this.textBox1.Text)
            };

            threadDriver.OnCountDown += new CountDownDriver.CountDown(threadDriver_OnCountDown);
            threadDriver.OnCountDownComplete += new CountDownDriver.CountDownComplete(threadDriver_OnCountDownComplete);

            new Thread(() => threadDriver.StartCountDown()).Start();

Thus, when these Events are fired inside the Threads, the Application is notified and the Event Handler executes. In this demo, the code in the Event Handlers prints to the UI. Note: Invoke has to be used to acquire the UI Thread first before writing to it.

        void threadDriver_OnCountDown(object o, EventArgs e)
        {
            int Count = (int)o;

            this.Invoke(new MethodInvoker(delegate()
            { this.richTextBox1.Text = this.richTextBox1.Text + "\n"
                                         + "Count Down : " + Count.ToString();
            }));
        }

threads.gif

Up Next
    Ebook Download
    View all
    Learn
    View all