Well I've searched a lot for a solution to this. I'm looking for a clean and simple way to prevent the callback method of a System.Threading.Timer from being invoked after I've stopped it.
I can't seem to find any, and this has led me, on occassion, to resort to the dreaded thread-thread.sleep-thread.abort combo.
Can it be done using lock?
start() is a function that is used to initialize a timer. To end or quit the timer, one must use a cancel() function. Importing the threading class is necessary for one to use the threading class. The calling thread can be suspended for seconds using the function time.
Timer is not thread-safe.
System. Threading. Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed.
Yes, they run in a different thread.
An easier solution might to be to set the Timer
never to resume; the method Timer.Change can take values for dueTime
and period
that instruct the timer never to restart:
this.Timer.Change(Timeout.Infinite, Timeout.Infinite);
Whilst changing to use System.Timers.Timer
might be a "better" solution, there are always going to be times when that's not practical; just using Timeout.Infinite
should suffice.
like Conrad Frix suggested you should use the System.Timers.Timer
class instead, like:
private System.Timers.Timer _timer = new System.Timers.Timer(); private volatile bool _requestStop = false; public constructor() { _timer.Interval = 100; _timer.Elapsed += OnTimerElapsed; _timer.AutoReset = false; _timer.Start(); } private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e) { // do work.... if (!_requestStop) { _timer.Start();//restart the timer } } private void Stop() { _requestStop = true; _timer.Stop(); } private void Start() { _requestStop = false; _timer.Start(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With