Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliably stop System.Threading.Timer?

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?

like image 999
JayPea Avatar asked Jun 16 '11 22:06

JayPea


People also ask

How do you stop a timer thread?

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.

Is system threading timer thread safe?

Timer is not thread-safe.

What is System threading timer?

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.

Does system timers timer run in a separate thread?

Yes, they run in a different thread.


2 Answers

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 image 129
Owen Blacker Avatar answered Sep 18 '22 14:09

Owen Blacker


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(); } 
like image 21
Jalal Said Avatar answered Sep 16 '22 14:09

Jalal Said