tags:

views:

1179

answers:

4

Hello,

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, it's on going. Is there a way to stop it after one go? or after 5 go's?

Right now i am 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();
        }
    }
}
A: 

Use System.Threading.Timer and specify a dueTime but specify a period of Timeout.Infinite.

binarycoder
Hello sir, I have tried this way. But it seems to be using more cpu, rather than the one i have now. I guess i will just stick with what i have then?
AJ Ravindiran
A: 
public static void DoTimer(double interval, ElapsedEventHandler elapseEvent)
{
    aTimer = new Timer(interval);
    aTimer.Elapsed += new ElapsedEventHandler(elapseEvent);
    aTimer.Elapsed += new ElapsedEventHandler( (s, e) => ((Timer)s).Stop() );
    aTimer.Start();
}
Joel Coehoorn
In what is this different what he did besides the fact that you fire two handlers when elapsed?
codymanix
He can now never start the timer again without it stopping after a single interval
Yuriy Faktorovich
@cody: the 2nd handler stops the timer, so that the event only fires once. That's exactly what he asked for. To run it five times, just add that as a parameter to DoTimer. The lambda expression would create a closure so it would work as expected. @Yuriy: He couldn't restart that timer again anyway: the variable was local to the DoTimer method.
Joel Coehoorn
+5  A: 

Why don't you just have an int counter that initially start out at 0 and is incremented every time the ElapsedEventHandler is fired? Then you simply add a check in the event handler to Stop() the timer if the counter exceeds the number of iterations.

Ian Kemp
+3  A: 

It is not on going the way you have it now. The Elapsed event is raised once and stops because you have called Stop. Anyway, change your code like the following to accomplish what you want.

static void Main()
{
  DoTimer(1000, 5, (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();
}
Brian Gideon