This is a more complex example of using the c# thread pool in a windows forms application. The goal here is to background a task but still keep some / part of the interface active and not freeze as a task is running.

To get this example to work you will need to create a project and create a button and a text box. I have used btnRun and txtCount in this example. The real purpose of this example is to demonstrate how to disable / enable the gui and to background the task as well as provide status updates to the interface from the background task and to handle an error should it occur.

I should probably point out that you cannot directly update the forms gui in c# from a background thread. The Forms part of the .net frame work is not thread safe. If you attempt to do so it will however create an error such as, Cross-thread operation not valid: Control 'txtCount' accessed from a thread other than the thread it was created on.

To get around this issue you can test the property InvokeRequired. If this property is true then you know that you should not update the interface directly. Knowing this it is possible to still create functions that can still perform the functions on either the main program thread or the background thread by calling invoke when the InvokeRequired properly is true. When Invoke is called the framework will send a message then call the function on the correct thread.

The following example shows this.

public partial class frmMain : Form
{
        public frmMain()
        {
                InitializeComponent();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
                SetGUI(false);
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.Run), null);
        }

        void Run(object args)
        {
                try
                {
                        for (int i = 0; i < 10; i++)
                        {
                                UpdateStatus(i.ToString());
                                Thread.Sleep(1000);
                        }
                        UpdateStatus("Complete");
                }
                catch (Exception ex)
                {
                        MessageBox.Show(ex.Message);
                }

                SetGUI(true);
        }

        void UpdateStatus(object args)
        {
                if (InvokeRequired)
                {
                        Invoke(new WaitCallback(UpdateStatus), args);
                        return;
                }

                txtCount.Text = (string)args;
        }

        void SetGUI(object args)
        {
                if (InvokeRequired)
                {
                        Invoke(new WaitCallback(SetGUI), args);
                        return;
                }

                btnRun.Enabled = (bool) args;
        }
}


Did You find this page useful?

Yes No



Last Modified: 20 February 2017

Releated Posts


2011-10-27 - CSharp - Number Of Cores and Processors
2011-10-04 - CSharp - Thread Queue Example
2011-09-29 - CSharp - Background Thread / Task
2011-09-17 - CSharp - Lookup Hostname
2011-08-29 - CSharp - IsGuid
2011-08-29 - C Sharp - StopWatch, The high resolution timer
2011-08-26 - CSharp - Convert Between Meters and Feet
2011-08-23 - CSharp - ThreadPool and Windows Forms
2011-08-10 - C Sharp - MD5Sum / SHASum
2011-07-22 - CSharp - Fibonacci sum
2011-07-13 - CSharp - Palindrome
2011-07-11 - CSharp - The string Reverse
2011-07-10 - CSharp - Interviews FizzBuzz
2011-06-27 - CSharp - HowTo Parse a URL
2011-06-22 - CSharp - Extending any class
2011-06-13 - ASPNET - Login by username or email
2011-05-12 - CSharp - ASPNET Logoff
2011-03-07 - C Sharp - Windows Logoff
2011-03-02 - ASPNET - Dynamic Controls
2011-03-01 - C Sharp - Resize an image by size of height
2011-02-23 - C Sharp / MSSQL Get inserted value of NEWSEQUENTIALID()
2011-02-10 - CSharp - Shutdown or reboot windows
2011-02-10 - CSharp - Wake on Lan (WOL) Packet
2011-02-06 - C Sharp - Gridview Bound Yes No
2011-02-05 - MSSQL - Levenshtein
2011-01-30 - MSSQL - Enabling CLR Functions
2011-01-30 - MSSQL - Adding MD5 checksum support
2011-01-30 - MSSQL - RegEx Support
2011-01-30 - MSSQL - Adding SHASum support