I'm still not sure that you really need that timer, as you did not really explain the purpose, but if you do, the best way is not using
System.Windows.Forms.Timer
. There are at least three more timers in .NET, and this one is the worst. You can use it only if you have no requirements to accuracy and can tolerate the 100% or more of timing error. The only one good but questionable feature of this timer is that its use is simplified: its tick event handler is also called in UI thread, which is, in your case, also a hassle. (However, you did not tag your UI library, so I'm not sure you tried to work with
System.Windows.Forms
, but I think this is pretty likely.)
You can choose from
System.Threading.Timer
,
System.Timers.Timer
or
System.Windows.Threading.DispatcherTimer
(WPF). Most likely, you would rather prefer
System.Timers.Timer
:
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx[
^].
The only difficulty is: this timer tick event handler is not guaranteed to be called in the UI thread, so you will need to use the same very invocation mechanism you would use in a non-UI thread to delegate some UI operation to be executed in the UI thread. You cannot call anything related to UI from non-UI thread. Instead, you need to use the method
Invoke
or
BeginInvoke
of
System.Windows.Threading.Dispatcher
(for both Forms or WPF) or
System.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[
^],
Control events not firing after enable disable + multithreading[
^].
—SA