You should be using System.Timers.Timer
, that will run in a seperate thread, See this MSDN article:
From above link:
System.Windows.Forms.Timer
If you're looking for a metronome, you've come to the wrong place. The timer events raised by this timer class are synchronous with respect to the rest of the code in your Windows Forms app. This means that application code that is executing will never be preempted by an instance of this timer class (assuming you don't call Application.DoEvents).
System.Timers.Timer
The .NET Framework documentation refers to the System.Timers.Timer class as a server-based timer that was designed and optimized for use in multithreaded environments. Instances of this timer class can be safely accessed from multiple threads. Unlike the System.Windows.Forms.Timer, the System.Timers.Timer class will, by default, call your timer event handler on a worker thread obtained from the common language runtime (CLR) thread pool. This means that the code inside your Elapsed event handler must conform to a golden rule of Win32 programming: an instance of a control should never be accessed from any thread other than the thread that was used to instantiate it.
Working Code:
public partial class Form1 : Form
{
System.Timers.Timer tmr = new System.Timers.Timer(1000);
volatile int timer;
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
timer = 0;
tmr.Elapsed += new System.Timers.ElapsedEventHandler(tmr_Elapsed);
tmr.Start();
while (timer < 2) ;
tmr.Stop();
Console.WriteLine("timer ends");
}
void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine(timer);
timer++;
}
}