I normally avoid using local variables to hold references to timers because when the local variable goes out of scope the timer gets garbage collected and stops firing. However, I ran into a bit of code that seems to get around this problem by referencing the timer itself through a closure in a lambda expression that is attached to the Elapsed
event.
{
var bkgTimer = new System.Timers.Timer(timeDelay) {AutoReset = false};
bkgTimer.Elapsed += (sender, args) => Handler(e, bkgTimer);
bkgTimer.Start();
}
Then later, in the Handler:
private void Handler( ... timer)
{
...
timer.Dispose();
}
It appears to work. Are there any problems with this approach? I wondered if it could lead to a memory leak since I don't understand what the lifetime of the lambda closure is controlled by.