If I have an active System.Threading.Timer and I set it to null, is it stopped?
I realize that it is more proper to call .Dispose() but I would like an answer to the question as written.
public class Foo
{
private System.Threading.Timer _timer;
public Foo()
{
// initialize timer
}
public void KillTimer()
{
_timer=null;
}
}
Update:
After much back and forth about whether setting a single reference to a System.Threading.Timer to null will indeed result stopping it have shown that
- there are no lingering references, e.g. events list, as a threading timer takes a sinlge callback and does not expose events.
- that if GC collects, the finalizer will indeed dispose the TimerBase and stop the timer.
spike
using System;
using System.Threading;
namespace SO_3597276
{
class Program
{
private static System.Threading.Timer _timer;
static void Main(string[] args)
{
_timer = new Timer((s) => Console.WriteLine("fired"), null, 1000, Timeout.Infinite);
_timer = null;
GC.Collect();
Console.ReadKey();
}
}
}
The timer callback is not called. Remove GC.Collect() and the callback is called.
Thanks all.
Not necessarily. Setting it to null, removes any references to it, and relies on the garbage collector to dispose of it.
If the timer went off before the GC got to it, it would trigger the event.