Threading in Windows Forms -- Sample Code

There's nothing quite like the experience of being in another country, even if most Americans do think of it as the 51st state.  At VSLive in Toronto I learned quite a bit including that friendly countries like Canada don't merge, they "squeeze"... just before running you off the road and watching you die in a firey ball of twisted metal.  Seriously, the drivers up there seem to want to die and they want to take as many people with them as they can.  Personally, I blame Tim Horton.  But I digress...

I gave two talks in Toronto, the first on threading in Windows Forms and I think it went very well.  I'm including the code from the demos with this post.  My second talk on Click-Once deployment had some technical issues, but otherwise I think went well.  That code is still a bit of a work in progress so I'll be posting it later when all of the features are complete.

I wanted to clarify a couple of things from my talk also.  I was asked if a thread can be set to run on a specific processor in a multiprocessor machine.  Threads can be set to run on a specific CPU in a multi CPU system by using the Process and ProcessThread classes in the System.Diagnostics namespace and setting the ProcessorAffinity mask.

Also, there was a question in the synchronization of the threads used to update the status bar text in the final demo.  I was using Application.DoEvents to slow down the processing that occurred after all of the asynchronous WaitHandles had been signaled.  What is actually happening is that when EndInvoke is called on the final background thread, the code that is waiting for the threads to complete gets executed, in this case changing the text of the status bar to "Done".  However, on the background thread after EndInvoke was being called, I was doing some other logic including adding tabs to a control and then setting the status bar text to show the user which city's weather had been loaded.  This processing was taking more time than the code which executes when the WaitHandles are signaled and so it would apear as if the "Done" message never showed up.  I used Application.DoEvents just to slow that thread down so that the others could catch up.  If I truly cared about the order of the status bar messages, I would have used my own WaitHandles and and signaled them manually after the tabs had been added to the control.

Download the Threading in Windows Forms Demo Code  

No Comments