I wanted to perform some operation repeatedly in 200ms interval , starting from time t=0 to t=10 sec.
Currently I am keeping track of elapsed time in a variable. This looks uncomfortable to me. Below is the code-
using System;
using System.Timers;
class Program
{
static int interval = 200; // 0.2 seconds or 200 ms
static int totalTime = 10000; // 10 seconds or 10000 ms
static int elapsedTime = 0; // Elapsed time in ms
static Timer timer;
static void Main(string[] args)
{
timer = new Timer(interval);
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Enabled = true;
Console.ReadKey(); // for checking
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (elapsedTime > totalTime)
timer.Stop();
else
{
// here I am performing the task, which starts at t=0 sec to t=10 sec
}
elapsedTime += interval;
}
}
Kindly suggest, if there exist any better way to perform the same task. Sample code is always appreciated.
It would have already queued before you have called Stop method. It will fire at the elapsed time. To avoid this happening set Timer. AutoReset to false and start the timer back in the elapsed handler if you need one.
That's all; just build it and run your project, after clicking the "Start Timer" Button you will see that a Message Box is displayed every 5 seconds. If you want to stop that, just press the "Stop Timer" Button and your timer will be stopped.
You can call timer1. Stop() to stop the timer.
You should stop the timer in your event and start again, just to make sure that your execution doesn't enter the event twice. Like:
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
timer.Stop();
if (elapsedTime > totalTime)
{
return;
}
else
{
// here I am performing the task, which starts at t=0 sec to t=10 sec
timer.Enabled = true; //Or timer.Start();
}
elapsedTime += interval;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With