I removed the last post as the formatting was horrible. Here again is my first demo app with the Synchronization facility. It is normally quite painful to try to make your WinForms application threadsafe. VS2005 made it much easier to see that you are doing something wrong. Your application will move along and then the debugger will break and you have a window with an InvalidOperationException in you face.
System.InvalidOperationExceptionwasunhandledMessage="Cross-thread operation not valid: Control 'richTextBox' accessed from a thread other than the thread it was created on."Source="System.Windows.FormsStackTrace:atSystem.Windows.Forms.Control.get_Handle()atSystem.Windows.Forms.RichTextBox.StreamIn(Streamdata,Int32flags)atSystem.Windows.Forms.RichTextBox.StreamIn(Stringstr,Int32flags)atSystem.Windows.Forms.RichTextBox.set_Text(Stringvalue)atSafelyUpdatingWinForm.MainForm.UpdateTime()inC:SafelyUpdatingWinFormSafelyUpdatingWinFormMainForm.cs:line38atSafelyUpdatingWinForm.MainForm.UpdateLoop()inC:SafelyUpdatingWinFormSafelyUpdatingWinFormMainForm.cs:line27atSystem.Threading.ThreadHelper.ThreadStart_Context(Objectstate)atSystem.Threading.ExecutionContext.Run(ExecutionContextexecutionContext,ContextCallbackcallback,Objectstate)atSystem.Threading.ThreadHelper.ThreadStart()
The IDE is nice enough though to point you in the direction of a solution How to: Make Thread-Safe Calls to Windows Forms Controls (MSDN). They suggest that for any component you want to change that you create delegates and try to use Control.Invoke to make the call on the appropriate thread. This gets very bloated when you have a large and complex UI. To simplify things, Craig Neuwirt created a new facility to plug into the Castle WindsorContainer. It can automatically martial the calls to the UI thread for you and a whole lot more. Roy Osherove has his own implementation that uses the DynamicProxy2.