Say if I listen for an event:
Subject.NewEvent += delegate(object sender, NewEventArgs e)
{
//some code
});
Now how do I un-register this event? Or just allow the memory to leak?
Say if I listen for an event:
Subject.NewEvent += delegate(object sender, NewEventArgs e)
{
//some code
});
Now how do I un-register this event? Or just allow the memory to leak?
There is another question (of mine) which goes into this in some (too much) detail: Weak event handler model for use with lambdas.
However, now that the Reactive Framework has come out, I'd seriously consider looking into that in this kind of situation.
To remove the handler on first invocation:
If you need to unregister an event, I recommend avoiding anonymous delegates for the event handler.
This is one case where assigning this to a local method is better - you can unsubscribe from the event cleanly.
Give your instance of the anonymous delegate a name:
Do you need to un-register it for a reason other than leakage?
Regarding the "Or just allow the memory to leak" bit, when Subject is cleaned up by the Garbage Collector, your anonymous delegate should be cleaned up as well, so there shouldn't be a leak.
You need a name for your anonymous function, and then, you can only do it as long as the name is in scope: