If object A listens to an event from object B, object B will keep object A alive. Is there a standard implementation of weak events that would prevent this? I know WPF has some mechanism but I am looking for something not tied to WPF. I am guessing the solution should use weak references somewhere.
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- C# GC not freeing memory [duplicate]
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
What advantages does Dustin's implementation have compared to the WPF's WeakEventManager class which simply wraps the target object as well as the delegate into a weak reference:
In my opinion this approach is more flexible, since it does not require the implementation to pass the target instance as a parameter during the invocation of the event handler:
This also allows the use of anomymous methods instead of an instance method (that seems to be also a disadvantage of the Dustin's implementation).
Using the recommended Dispose() pattern, where you consider events a managed resource to clean up, should handle this. Object A should unregister itself as a listener of events from object B when it's disposed...
There's also a solution that works in Silverlight/WP7 which uses Linq expressions instead of MSIL emit.
http://socialeboladev.wordpress.com/2012/09/23/weak-event-implementation-that-works-for-any-event-type/