C# · Dotnet

Progress Modal Dialog Launch from another Thread

Dear,

Today i encountered a problem to fit one of the use case, so i went ahead to develop a prototype. Because of rest of the layering architecture i had to take a bad design decision. I had to launch a progress dialog as modal dialog on top of the main window but do not block the main window thread from further data processing. So i had to launch this progress dialog in a different child thread and make the main window as its parent. The main thread shall do alot of processing and notifies the progress dialog about the updates. Basically the below layers in the main thread calculates some data and informs it to the UI  for displaying. To accommodate this i tried couple of ways and reached dead-end. Referring to couple of stackover flow threads also did not give me complete answer, but they indeed gave me some insights. Thanks to those guys.

So i came up with a prototype with a simple winform main app having a button which again creates a progress dialog as modal in a separate thread then update progress bar values from the main thread. Below is rough diagram of how it should be:

progress Dlg

So after exhaustive effort for a day, i came up with below code which seem to work out well as per the stated requirement above. Below is the code:

public class MainForm1 : Form
    {      
        int counter = 0;
        Thread progressDialogUIThread;
        bool stopProcessing = false;
        ManualResetEvent resetEvent = new ManualResetEvent(false);
       
        ProgressDialogForm2 progressDlg;

        private void button1_Click(object sender, EventArgs e)
        {           
            progressDialogUIThread = new Thread(new ThreadStart(InitializeDialog));
            this.Enabled = false;
            progressDialogUIThread.Start();
           //Wait till child thread creates and initialize the dialog instance
            resetEvent.WaitOne();
            UpdateProgressData();
        }

        private void InitializeDialog()
        {
            progressDlg = new ProgressDialogForm2();           

            progressDlg.cancelButtonEvent = new EventHandler((s, e1) =>
            {
                switch (progressDlg.DialogResult)
                {
                     case DialogResult.Cancel: 
                        stopProcessing = true;
                        progressDlg.Close();
                        break;
                }
            });

            resetEvent.Set();
            //Cant pass owner here, since child thread so throws cross thread excep.
            progressDlg.ShowDialog();
        }

        private void UpdateProgressData()
        {
            for (int i = 0; i < 100; i++)//Range of Progress bar is 0-100
            {
               //Closing dialog window on cancel button click, hence flag check. 
                if (!stopProcessing)
                  //If not checked, then window is closed and below invoke throws exception.
                {
                    progressDlg.Invoke(new Action<int>(progressDlg.SetProgressValue),
                           new object[] { i });
                    //Just to put some delay in updating progress bar for visiblity purpose
                    Thread.Sleep(500);
                }
                else this.Enabled = true;
            }
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
           if (progressDlg != null)
            {
                if (!stopProcessing)//When dialog is closed, nothing to update.
                    this.Invoke(new Action(progressDlg.BringToFront));
            }
        }
}

public partial class ProgressDialogForm2: Form
    {
        public EventHandler cancelButtonEvent;

         public void SetProgressValue(int value)
        {
            this.progressBar1.PerformStep();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            if(cancelButtonEvent != null)
                cancelButtonEvent(sender,e);
        }
    }

Hope it was helpful.

Happy Coding 🙂
Zen 🙂

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s