In short it is illegal in the Windows world for a (background) thread to control resources that it does not own/did not create. Sure, like speeding it’s not always caught or enforced, but when it is it is harsh.
The way to get around such an issue in this case is have the update to the progress bar occur in the context of it’s owning thread and you can manually detect if this is necessary by calling the InvokeRequired property of the progress bar to determine if a call to Invoke() is required.... this is however a little cumbersome so instead I’d suggest taking a look at BackgroundWorker.
With BackgroundWorker you’ve got a class that offers functionality similar to the ThreadPool only does the work behind the scenes so that if wired up properly, is thread safe.
Try this example based on your own:
BackgroundWorker bgw;
...
m_pb.Maximum = 10000;
bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
//Method to be called when worker is run
bgw.DoWork+=new DoWorkEventHandler(bgw_DoWork);
//Event handler called when progress is reported
bgw.ProgressChanged+=new ProgressChangedEventHandler(bgw_ProgressChanged);
//Run BackgroundWorker
bgw.RunWorkerAsync(m_pb.Maximum);
...
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int i = (int)e.UserState;
m_pb.Value = i;
m_lbl.Text = i.ToString();
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
int max = (int)e.Argument;
for (int i = 0; i <= max; i++)
{
bgw.ReportProgress(0, i);
}
}