简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM