Wondering if someone can answer something that has stumped me.
I have a Timer that sets a variable to let some other threads know when to stop execution (the length is hard coded for this example)
Timer endProcessingThread = new Timer(x => _endOfProcessingTimeHasElapsed = true, null, 10000, 0);
I don’t ever join on the thread or use the timers variable name for anything so I ‘cleaned’ it up to say:
new Timer(x => _endOfProcessingTimeHasElapsed = true, null, 10000, 0);
This compiles fine but the thread never executes.
Anyone know why?
First of all:
TimerisIDisposable, so that you should use the timer’s variable name, at least to dispose it properly.And: Since you do not keep any reference to the created instance, it is eligible for garbage collection. And since the internals of the Timer use a finalizer, the finalizer gets called and the timer gets deleted before it had a chance to fire. (Note that just keeping a reference in a named local variable as in your first case is not enough, the compiler might notice the variable is not used at all and garbage collect the instance anyway.)
Solution: Keep the reference and call
Dispose()as soon as you finished using it.