I would do it via a separate thread, which is more reliable way. It depends on purpose though. Some inaccuracy in time can be compensated be taking real time reading in each iteration of a loop. It's good, for example, to make impression of smooth motion; in other cases it is not good. You can even create a realistic clock, but you would need a delay (
Thread.Sleep
) somewhat smaller then the period of time for an update a clock view.
With a timer, you need to be more careful. First idea is: you probably need some near-periodic behavior. If so, make sure you never use the timer type
System.Windows.Timer
: it is simple and guarantees that the event handler is called in the UI thread, but its timing accuracy is prohibitively bad. It can be used for, say, implementing of timeouts when accuracy is not critical at all.
Let's come back to other timers which can give you reasonable accuracy. They cannot guarantee the call of your handler method in your UI thread. You have to take it into account. 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:
.NET event on main thread,
How to get a keydown event to operate on a different thread in vb.net,
Control events not firing after enable disable + multithreading.
—SA