Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the expected behavior of a locally scoped Timer?

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;
like image 822
Matt Avatar asked Feb 03 '23 17:02

Matt


2 Answers

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

like image 170
InBetween Avatar answered Feb 05 '23 06:02

InBetween


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.

like image 35
Jamie Avatar answered Feb 05 '23 07:02

Jamie