Question

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.

Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top