Search code examples
.neteventsgarbage-collectionweak-references

Weak events in .NET?


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.


Solution

  • Dustin Campbell from the DidItWith.NET blog examines several of the failed attempts to create weak event handlers, then goes on to show a valid, working, lightweight implementation: Solving the Problem With Weak Event Handlers.

    Ideally, though, Microsoft would introduce the concept into the language itself. Something like:

    Foo.Clicked += new weak EventHandler(...);
    

    If you feel this feature is important to you, please vote for it here.