How to handle the cross-threaded error in the C sharp Windows application?

advertisements

I'm having an application with a progress bar and a buttom.

When the button clicked the progress bar value will get increased, here is the source code,

private void Run()
        {
                progressBar1.Maximum = 1000;
                progressBar1.Minimum = 0;
                progressBar1.Step = 1;

                for (int l_nIndex = 0; l_nIndex < 1000; l_nIndex++)
                {
                        progressBar1.Value++;
                        Thread.Sleep(10);
                }
            }

private void button1_Click(object sender, EventArgs e)
        {
                Run();
    }

so when i run the application, the progress bar value is getting increased, but when i try to move the window its not responding.

I can not run it in a normay thread way - it will throw Cross-Thread error.

so i changed the code like,

private void Run()
        {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(this.Run));
                }
                else
                {
                    progressBar1.Maximum = 1000;
                    progressBar1.Minimum = 0;
                    progressBar1.Step = 1;
                    for (int l_nIndex = 0; l_nIndex < 1000; l_nIndex++)
                    {
                            progressBar1.Value++;
                            Thread.Sleep(10);
                    }
                }
        }

 private void button1_Click(object sender, EventArgs e)
        {
                Thread myThread = new Thread(new ThreadStart( Run));
              myThread.Start();
        }

Now i can able to move the winodow, but when i move the progress bar is stopped, and when i release the mouse button its resuming. So still the execution is in UI Thread. How to handle it in a better way.Please help me to do this .


Invoke() works by running the given delegate from the UI thread. So if you use Invoke() to run your entire method, then your entire method runs from the UI thread.

Instead, you should be doing your actual work in the other thread, and just performing UI updates in the UI thread, by just Invoke()ing the little bits of code that perform the updates.

One easy way to do this is to use the BackgroundWorker class built into the standard library.