Search code examples
c#wpfweak-references

What is the use of RemoveHandler in Weak Event Pattern?


As per Microsoft doc:

The weak event pattern can be used whenever a listener needs to register for an event, but the listener does not explicitly know when to unregister.

A sample code here illustrates that when using WeakEventManager, not explicitly calling RemoveHandler will not cause memory leak.

So my question is, why is the method RemoveHandler even there in WeakEventManager class? Isn't it completely unnecessary? When it becomes necessary?


Solution

  • Isn't it completely unnecessary?

    No. How are you supposed to unsubsribe (explicitly) if there isn't a RemoveHandler method?

    When it becomes necessary?

    Whenever you want to unsubsribe from the event subscription explicitly.

    If you don't call RemoveHandler, the event handling continues until the garbage collecor collects the listener.