C # timer class - stop after a certain number of fires
I've been looking into the Timer class ( http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx ) but the thing about the timer is what happens. Is there a way to stop it after one? or after 5 go?
I am currently doing the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
namespace TimerTest
{
class Program
{
private static System.Timers.Timer aTimer;
static void Main(string[] args)
{
DoTimer(1000, delegate
{
Console.WriteLine("testing...");
aTimer.Stop();
aTimer.Close();
});
Console.ReadLine();
}
public static void DoTimer(double interval, ElapsedEventHandler elapseEvent)
{
aTimer = new Timer(interval);
aTimer.Elapsed += new ElapsedEventHandler(elapseEvent);
aTimer.Start();
}
}
}
+2
source to share
5 answers
This is not how it is now. The Elapsed event is raised once and stops because you called Stop. Anyway, change your code as follows to accomplish what you want.
private static int iterations = 5;
static void Main()
{
DoTimer(1000, iterations, (s, e) => { Console.WriteLine("testing..."); });
Console.ReadLine();
}
static void DoTimer(double interval, int iterations, ElapsedEventHandler handler)
{
var timer = new System.Timers.Timer(interval);
timer.Elapsed += handler;
timer.Elapsed += (s, e) => { if (--iterations <= 0) timer.Stop(); };
timer.Start();
}
+5
source to share
By creating an object of this class, you can use a timer in any class
public class timerClass
{
public timerClass()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 5 seconds.
aTimer.Interval = 5000;
aTimer.Enabled = true;
}
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.Writeln("Welcome to TouchMagix");
}
}
0
source to share