Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsubscribe Lambda Event Handler **With Closure**

I know a lot of people have asked the question of "how do I unsubscribe the following"

myButton.Click += (s, e) => MessageBox.Show("Hello World!");

With the obvious answer of

EventHandler HelloWorld = delegate { MessageBox.Show("Hello World!"); };
myButton.Click -= HelloWorld;
myButton.Click += HelloWorld;

But what I'm using a lambda to create a closure? What if my object has an event called AssessmentRationChanged that is of type Action, and I'm wiring it thusly:

foreach (MassFMVUpdateDTO dto in CurrentProperties)
   dto.AssessmentRationChanged += () => setCellColorBasedOnAssessmentRatioValue(dto);

What if there's a chance I've already set this handler for some / all of the objects in this loop? Is there a way to unsubscribe them?

I'm sure I could use reflection and clear the handler completely, but is there a cleaner way?

like image 309
Adam Rackis Avatar asked Mar 11 '11 15:03

Adam Rackis


1 Answers

No, you have to store the references to the delegates, basically.

Remember everything that you'll want to unsubscribe later.

like image 177
Jon Skeet Avatar answered Oct 20 '22 21:10

Jon Skeet