I have a question about timers and threads. I noticed that the timers misbehaving when started within the threads, while the timers are part of the Winform.
Generally I’m interested in problems related threads and timers.
Happy New Year to you all, the answers may be to wait until 2011:)
Sounds like you’re using a
System.Threading.Timerand using aTimerCallbackthat performs GUI updates. Is that it?There are a number of correct ways to deal with this. Use a
System.Windows.Forms.Timerand handle itsTickevent if you’re looking to update the UI. Use aBackgroundWorker, do non-UI work in itsDoWorkevent and then perform UI updates in itsRunWorkerCompletedevent if you’re performing long-running background tasks.In general, the important thing to understand about multithreading as it pertains to Windows Forms is this: all Windows Forms application have a UI thread, which is the only thread that is allowed to perform UI updates. It is continually processing a queue onto which user actions are pushed and handle via events. When you try to do anything that updates a UI control from any thread besides this thread, you get an exception because this behavior was not planned for in the design of Windows Forms components, and would therefore very likely cause bugs or possibly crash the entire application.
So the approach to multithreading is generally to separate work into two parts, that which can be done in the background (on a non-UI thread) and that which must sent to the queue being processed by the UI thread so that it can be handled in a safe manner. The usefulness of types like
System.Windows.Forms.TimerandBackgroundWorkeris that they encapsulate many of the difficult details of this process for you, allowing you to focus on the code you want to run.That’s a high level view of how multithreading works with Windows Forms. I’m sure others can provide plenty of references pointing you to more information on the subject (and if nobody else does, maybe I can look some up later).