Specifically, if you create an instance of a Timer in the local scope, and then return from that scope:
1) Will the timer still execute?
2) When would it be garbage collected?
I offer these two scenarios:
Timer timer = new Timer(new TimerCallback((state) => { doSomething(); }));
timer.Change((int)TimeSpan.FromSeconds(30), (int)TimeSpan.FromSeconds(30));
return;
And
Timer timer = new Timer(new TimerCallback((state) => { doSomething(); }));
timer.Change((int)TimeSpan.FromSeconds(30), Timeout.Infinite);
return;
The TimerCallback
has a reference to the method DoSomething()
, and therefore (in your example) to this
but there is no live reference going the other way so it should get collected...eventually
The timer might or might not execute, depends on whether garbage collection runs before the time executes. This is why it's good practice to keep a reference to the timer somewhere other than on the stack.
Note that this is not always problematic; for example, threads won't be collected as long as they are still running.
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