views:

62

answers:

1

I have a custom control whose primary purpose is to draw data. I want to add a ScheduleUpdate(int milliSeconds) method to the control which will force an update X milliseconds from now.

Since this is all GUI land, I should be using a Windows.Forms.Timer, but how does this timer instance know which thread it belongs to? What if ScheduleUpdate() is called from a non-UI thread?

Should I construct the timer in the Control constructor? Or perhaps the Load event? Or is it safe to postpone construction until I'm inside ScheduleUpdate()?

I know there are some very similar questions about this already, but I don't have a Timer component on my control, I'm constructing it on a when-it's-needed basis.

+1  A: 

It knows because it is aware on which thread it was created. There's an invisible helper window that receives the WM_TIMER message, which in turn triggers the Tick event. The window has thread affinity, the message loop on the thread dispatches the message. Which should be the UI thread of your app.

Make sure you create this timer on the same thread as the form and its controls. Just drop it on the form or create it in the form or control constructor. You then just need to set the timer's Enable property to true. That's thread-safe, you can do this on the scheduler thread.

Hans Passant