-2

I have a System.Timers.Timer with 100 interval. my question is that if I set enable = false in timer, is current working process in timer method stop immediately? or after method finished.

private void watchTags(object obj, ElapsedEventArgs handler)
    {
        for(int i=0 ; i<10000;i++){
            // some works
        }
    }
private void stop_button(){
    watcher.Enabled = false;
}

is my loop immediately stop or after finish?

nariman amani
  • 263
  • 6
  • 21

5 Answers5

0

Doing timer.Enabled = false would stop Timer. Its same as timer.Stop();

timer.Enabled = false = System.Threading.Timer or System.Timers.Timer

timer.Stop(); =System.Windows.Forms.Timer

Jamil
  • 330
  • 1
  • 6
  • 25
0

If you are using System.Timers.Timer you can stop like this

timer.Enabled = false

if you are using System.Threading.Timer, use this

timer.Change(Timeout.Infinite , Timeout.Infinite)

Or use

timer.Stop(); 

if you are using System.Windows.Forms.Timer

Reference C# - how do you stop a timer?

Community
  • 1
  • 1
Litisqe Kumar
  • 2,512
  • 4
  • 26
  • 40
0

use timer.Stop(); or timer.Enabled = false;

Hope it helps.

0

Okay. as Vijay Kumbhoje said in comments when the timer is finished , any process in watchTags method immediately ends without finishing job.

nariman amani
  • 263
  • 6
  • 21
0

If someone in 2020 went here and see this accepted answer, it's not right. Elapsed event will not stop with timer.Stop(). This will only stop launching Elapsed event again, nothing else.

I think accepted answer in this thread doing it right: c# Task cancellation when using System.Timers

GhostVolume
  • 81
  • 1
  • 7