I will clarify about timers and the
Sleep
function.
1-
System.Threading.Sleep
blocks the calling thead
2- A
System.Threading.Timer
or a
System.Timers.Timer
executes from a dedicated thread, therefore
the callback will be called even if the thread which instanciated the timer is sleeping.
3- A
System.Windows.Forms.Timer
executes from the main thread, therefore
the callback will not be called if the main thread is sleeping.
Do this simple test to convince yourself:
static class Program
{
[STAThread]
static void Main()
{
}
static void TestThreading()
{
System.Threading.Timer timer = new System.Threading.Timer(
e => Console.WriteLine("Timer"),
null, 0, 1000);
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
timer.Dispose();
}
static void TestTimers()
{
System.Timers.Timer timer = new System.Timers.Timer(1000);
timer.Elapsed += (sender, e) => Console.WriteLine("Timer");
timer.Enabled = true;
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
timer.Dispose();
}
static void TestWinForms()
{
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += (sender, e) => Console.WriteLine("Timer");
timer.Enabled = true;
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
timer.Dispose();
}
}
For the
Windows.Forms.Timer
, you can replace the infinite sleep with a
Sleep(10)
inside a loop if you want, but it will not change anything since you are still inside your function. The callback will be called only if your main thread is
not busy.
Not busy here means you handled all UI events (button clicks, keyboards, ...) and you are waiting for the next event.