Showing posts with label PerformStep. Show all posts
Showing posts with label PerformStep. Show all posts

Friday, May 28, 2010

C#: Cross-thread operation not valid: Control ‘progressBar1’ accessed from a thread other than the thread it was created on

Error Message: Cross-thread operation not valid: Control ‘progressBar1’ accessed from a thread other than the thread it was created on.

This goes for any control that needs to be touched by a worker thread, you cannot do it directly.  You must do a callback so the main UI thread actually does the update.

Reproduce the problem:

        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;

            System.Threading.Thread worker = new System.Threading.Thread(doWork);
            worker.Start();
        }

        private void doWork()
        {
            for (int i = 0; i < progressBar1.Maximum; i++)
            {
                progressBar1.PerformStep();
            }
        }

Solution is:
Add this method, and instead of calling progressBar1.PerformStep(), call ActuallyPerformStep():
        delegate void CallPerformStep(ProgressBar myProgressBar);
        private void ActuallyPerformStep(ProgressBar myProgressBar)
        {
            if (myProgressBar.InvokeRequired)
            {
                CallPerformStep del = ActuallyPerformStep;
                myProgressBar.Invoke(del, new object[] { myProgressBar });
                return;
            }

            myProgressBar.PerformStep();
        }

And now the main UI thread is calling the UI Control.