Once the object goes out of scope, and there are no additional references to it. It will, eventually, be garbage collected. But this might not happen for a while. So, the timer will likely keep firing until it is eventaully garbage collected.
This is just a guess though, as I don't have the ability to test it at the moment.
UPDATE:
I just wrote a small test program that looks something like this:
static void Main(string[] args)
{
SetTimer();
Console.ReadLine();
}
private static void SetTimer()
{
Timer expirationTimer = new Timer(1000);
expirationTimer.Elapsed += (sender, e) => Notify(e);
expirationTimer.Start();
}
private static void Notify(ElapsedEventArgs e)
{
Console.WriteLine(string.Format("Notified! {0}", e.SignalTime));
}
The timer keeps firing for a long time (i eventually just ended the program). Interestingly enough, i inserted a 15 second sleep in the main function, then called GC.Collect()
and the timer kept running even after the forced garbage collection, although there is no guarantee that calling GC.Collect()
will actually do anything.
I also tried wrapping the timer in a using statement, and that correctly disabled the timer right away (did not print anything to the screen). So, I believe my assumption is correct that garbage collection will eventually collect the timer, and dispose of it. but there is no way to determine when that will be.