Weak event handler model for use with lambdas
Posted
by Benjol
on Stack Overflow
See other posts from Stack Overflow
or by Benjol
Published on 2009-11-17T07:49:41Z
Indexed on
2010/03/22
8:51 UTC
Read the original article
Hit count: 441
OK, so this is more of an answer than a question, but after asking this question, and pulling together the various bits from Dustin Campbell, Egor, and also one last tip from the 'IObservable/Rx/Reactive framework', I think I've worked out a workable solution for this particular problem. It may be completely superseded by IObservable/Rx/Reactive framework, but only experience will show that.
I've deliberately created a new question, to give me space to explain how I got to this solution, as it may not be immediately obvious.
There are many related questions, most telling you you can't use inline lambdas if you want to be able to detach them later:
- Weak events in .Net?
- Unhooking events with lambdas in C#
- Can using lambdas as event handlers cause a memory leak?
- How to unsubscribe from an event which uses a lambda expression?
- Unsubscribe anonymous method in C#
And it is true that if YOU want to be able to detach them later, you need to keep a reference to your lambda. However, if you just want the event handler to detach itself when your subscriber falls out of scope, this answer is for you.
© Stack Overflow or respective owner