Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop timer after some time in C#

Tags:

c#

timer

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.

like image 986
Ravi Joshi Avatar asked May 06 '14 16:05

Ravi Joshi


People also ask

How do I stop a timer elapsed event?

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.

How to Stop timer in c# windows application?

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.

How do you stop a timer in Visual Studio?

You can call timer1. Stop() to stop the timer.


Video Answer


1 Answers

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;
}
like image 132
user2711965 Avatar answered Sep 28 '22 04:09

user2711965