JKennedy
JKennedy

Reputation: 18799

How do I unhook an lambda event handler inside the lambda method?

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?

Upvotes: 3

Views: 346

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127583

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.

Upvotes: 5

Related Questions