System.Windows.Forms.Timer not firing

时光怂恿深爱的人放手 提交于 2019-12-04 15:21:54
noseratio

I initially meant to post this as comment, but it turned to be too long.

Firstly, your thread structure is a bit confusing to me, the way you described it. Put Debug.WriteLine("OnEvent:" + Thread.CurrentThread.ManagedThreadId) inside OnEvent and let us know all thread IDs you see from your debug output.

That said, the rules are:

  • You should create WinForms' Timer object on an STA thread, and the thread should be configured as STA before it starts.

  • This thread may or may not be the main UI thread (where your main form was created), but it still should execute a message loop (with Application.Run) for timer events to fire. There are other ways of pumping messages, but generally you do not control them from .NET code.

  • You should handle the events sourced by WinForms' Timer on the same thread it was created. You can then 'forward' these events to another thread context if you like (using SynchronizationContext Send or Post) but I can't think of any reasons for such complexity.

The answer by @Maarten actually suggests the right way of doing it, in my opinion.

The winforms timer is a control and must be used by placing it on a form. You never add it to a control-collection, so I would not expect it to work properly. The documentation says the following

Implements a timer that raises an event at user-defined intervals. This timer is optimized for use in Windows Forms applications and must be used in a window.

Therefore, I would suggest that you use an instance of the System.Timers.Timer class. This class can be used anywhere.

Note that the Tick-event you use above, is called by another name in the System.Timer.Timer class, namely the Elapsed-event.

I don't yet understand why the Forms.Timer doesn't operate as expected but the following excellent article explains in detail how to marshal work onto the UI thread: http://www.codeproject.com/Articles/31971/Understanding-SynchronizationContext-Part-I

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!