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
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.
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.