The procedure Shahin showed would work correctly if called from the event handler of the event
System.Windows.Forms.Timer.Tick
. Let's say, this is a method called
SwitchImageVisibility
. Now, a problem with this timer is that it is incredibly inaccurate. If it's fine for your purpose, use it, but I warn it: the errors could be so bad that a user may clearly see that a timer behavior is not periodic.
This lack of accuracy can be unbelievably bad. The lack of periodic behavior can be visible with unarmed eye and very irritating. I would recommend to use this timer in rare cases when accuracy does not matter, and this is not your case. (One case when such a random delay is expected: flash screen or something like that, when the event is handled only once.)
If you create a separate thread with periodic behavior and a delay using
System.Threading.Thread.Sleep(5000)
, it would be much better. Another approach would be using much more accurate timers,
System.Threading.Timer
or
System.Timers.Timer
. Please see:
http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx[
^].
But overall, using a thread instead of timer is safer and simpler.
The only benefit of
System.Windows.Forms.Timer
is that you can call UI methods/properties from its
Tick
handler, unlike all other cases.
You cannot call anything related to UI from non-UI thread (and other timers will work from a different thread, too). 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[
^].
So in your case, if you want to call
SwitchImageVisibility
in a method defined in a form or a control class, but in a non-UI thread, it will look like this:
this.Invoke(new Action(() => { SwitchImageVisibility(); }), null);
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