jimutt jimutt - 1 year ago 63
C# Question

C# timers.timer is not working properly

I'm trying to use a timer in C# to run a method at an interval of five seconds. Though this code doesn't seem to work. I do not get any errrors when running it but the program (I run this in a console) shuts down right after

. The timer1_Elapsed method is never getting executed. I know that because I've tried making the program print a string to the console at the first line of the timer1_Elapsed method.

class Program
Timer timer1 = new Timer();

static void Main(string[] args)
Program IP = new Program();
IP.timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
IP.timer1.Interval = 5000;
IP.timer1.Enabled = true;


static void timer1_Elapsed(object sender, ElapsedEventArgs e)
//Function to get executed each time the counter elapses.


Answer Source

The reason is that the Start method of the timer starts the timer on another thread, and immediately returns from the method. This causes your Main method to end, and the console to shut down.

Depending on what Timer you are using (there are a few similarly named classes in the BCL) you may want to implement the fix differently. I suggest reading the documentation on System.Timers.Timer, System.Windows.Forms.Timer or System.Threading.Timer depending on which it is you are using.