开发者

Timers and multithreading

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 p开发者_StackOverflowroblems 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.Timer and using a TimerCallback that performs GUI updates. Is that it?

There are a number of correct ways to deal with this. Use a System.Windows.Forms.Timer and handle its Tick event if you're looking to update the UI. Use a BackgroundWorker, do non-UI work in its DoWork event and then perform UI updates in its RunWorkerCompleted event 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.Timer and BackgroundWorker is 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).


Comparing the Timer Classes in the .NET Framework Class Library is a good article to read.


Google maybe?

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜