[c#] What is the best way to implement a "timer"?

What is the best way to implement a timer? A code sample would be great! For this question, "best" is defined as most reliable (least number of misfires) and precise. If I specify an interval of 15 seconds, I want the target method invoked every 15 seconds, not every 10 - 20 seconds. On the other hand, I don't need nanosecond accuracy. In this example, it would be acceptable for the method to fire every 14.51 - 15.49 seconds.

This question is related to c# .net-4.0

The answer is


It's not clear what type of application you're going to develop (desktop, web, console...)

The general answer, if you're developing Windows.Forms application, is use of

System.Windows.Forms.Timer class. The benefit of this is that it runs on UI thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.

If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.


Reference ServiceBase to your class and put the below code in the OnStartevent:

Constants.TimeIntervalValue = 1 (hour)..Ideally you should set this value in config file.

StartSendingMails = function name you want to run in the application.

 protected override void OnStart(string[] args)
        {
            // It tells in what interval the service will run each time.
            Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
            base.OnStart(args);
            TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
            serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
        }

By using System.Windows.Forms.Timer class you can achieve what you need.

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();


t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();

void timer_Tick(object sender, EventArgs e)
{
      //Call method
}

By using stop() method you can stop timer.

t.Stop();