So I looked on SO and found how to unhook anonymous event handlers and that is no problem. But the problem I have is how to unhook the event handler inside the instance of the event handler itself.
For example I have a timer:
System.Timers.Timer aTimer = new System.Timers.Timer();
System.Timers.ElapsedEventHandler handler = ((sender, args)
=>
{
//aTimer.Elapsed -= handler;
wc.CancelAsync();
});
aTimer.Elapsed += handler;
aTimer.Interval = 100000;
aTimer.Enabled = true;
With the line commented out this works fine. But then I realised there is a possible memory leak as the ElapsedEventHandler is never unhooked. I therefore tried to add the commented out line to my ElapsedEventHanlder to unhook the timer from itself.
But I cannot compile the code because of the error:
Use of unassigned local variable "handler"
Is it possible to unhook the Elapsed event of my Timer when my timer completes?
Split the declration and the assignment of your variable and it will work fine.
System.Timers.ElapsedEventHandler handler = null;
handler = ((sender, args)
=>
{
aTimer.Elapsed -= handler;
wc.CancelAsync();
});
The way variable capture works handler will not be null when the event fires, it will be the anonymous delegate.
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