The code below when run will show one timer event fired each time the timer
is enabled.
If you debug it and set a breakpoint in the tm_Elapsed function, however,
please note that timer events may be pending, as the timer can run on
another thread. This is probably the behavior you're seeing. You can get
this same behavior in run mode if you set the interval to something very
small, so that it fires again while the call to Console.WriteLine is
running.
Note the documentation:
"Note The event-handling method might be called even after the Stop method
is called. The event-handling method might run on one thread at the same
time that a call to the Stop method runs on another thread. This might
result in the Elapsed event being raised even after the Stop method is
called. To prevent this, use the SignalTime property to compare the time the
event was raised to the time the Stop method was called. If the event was
raised after the Stop method was called, do not process the event."
------------------------------------------------------------------
public class Class1
{
private static System.Timers.Timer tm;
[STAThread]
static void Main(string[] args)
{
tm = new System.Timers.Timer(2000);
tm.Elapsed += new System.Timers.ElapsedEventHandler(tm_Elapsed);
for(int i=0;true; i++)
{
System.Threading.Thread.Sleep(200);
if( (i % 20 ) == 0)
{
System.Console.WriteLine("Enabled");
tm.Interval = 400;
tm.Enabled = true;
}
}
}
private static void tm_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
System.Console.WriteLine("Stopped");
tm.Enabled = false;
tm.Interval = 300;
}
}
"Peter Johnsson" <lk@algonet.se> wrote in message
news:um**************@TK2MSFTNGP09.phx.gbl...
"Philip Rieck" <st***@mckraken.com> wrote in message
news:uT**************@TK2MSFTNGP11.phx.gbl... Seting the interval to anything greater than 0 (even what was previously set at) resets the timer (less than or equal to zero will throw an
exception). It will not re-enable the timer, however.
Thanks for your answer!
What's the difference between the timer being reset or re-enabled? The
timer do seems to be re-enabled (internally atleast) when a new Interval value
is assigned inside the event handler. However, its Enabled property doesn't
change to True when a value is assigned to Interval, even though it seems
to be enabled interally.
What you'll probably should do is set the timer's enabled to false in
your event handler, then in the code where you would have reset it, re-enable it.
Doesn't matter. The eventhandler will be called again even though I set
the enabled to false or calling the stop method, like
EventHandler:
mTimer.Interval = 10000;
mTimer.Enabled = false; // or mTimer.Stop().. doesn't matter..
Try it yourself :)