Anyone who has been doing any type of .net development knows you can subscribe (MSDN on event subscription) to an event as follows:
Subscribe to an Non-Anonymous Method
...
// instance class w/ an event
myClass.DoSomething += HandleDoSomething
...
// the method which handles the event
privat evoid HandleDoSomething( object s, args e )
{
// Logic goes here
}
Subscribe to an Anonymous Method
...
// instance class w/ an event
myClass.DoSomething += (s, e) => {
// logic goes here
}
And to unsubscribe from a non-anonymous method you would do the following
...
// instance class w/ an event
myClass.DoSomething -= HandleDoSomething
...
However, the problem comes in when you try to unsubscribe to an event subscription which was wired up w/ an anonymous method. You cannot do the following:
...
myClass.DoSomething -= (s, e) => {}
...
The reason the above does not work is that in order to unsubscribe to an event you need a memory pointer to a class instance.
However, there is a solution to our problem, you can do the following
EventHandler handler = null;
handler = (s, e) =>
{
// time to do something useful here
// the trick here is that you MUST un-subscribe inside your anonymous method.
myClass.DoSomething -= handler;
};
myClass.DoSomething += handler;
The reason the above works is because you have a class instance of our handler which we can use for both subscription and un-subscription.
Hope this helps.
Till next time
Posted
06-26-2011 9:20 AM
by
Derik Whittaker