Monday, February 23, 2004 12:42 AM
richard
How not to update a Windows Form from a Thread
Since we've been formulating skill-testing questions for new candidates for work lately, I've turned my mind towards what makes an interesting question - one that I would want to be asked. Here's some code that I wrote earlier today (and promtly changed after I discovered what it did) see if you can spot what's wrong before reading the paragraph below the code. This is running in a Windows form, handling a button click and the workerThread Thread tries to update the Form using this.Invoke(...)
private void Update_Click(object sender, System.EventArgs e)
{
updateProgress.Minimum = 0;
Thread workerThread = new Thread(new ThreadStart(updateAllSymbols));
workerThread.IsBackground = true;
workerThread.Start();
workerThread.Join();
}
Anyone see the error here? I'm so used to writing threaded console apps where I don't have any wierd stuff to do to show output that I automatically stuck the workerThread.Join() in there. Problem is, workerThread gets to a point where it wants to update the GUI (a progressbar, of course) and it calls Invoke(). Invoke tries to run my delegate on the GUI thread - but the GUI thread is sitting there, patiently trying to wait for my worker thread to finish. Join() method call removed, app works fine.