Search code examples
c#design-patternsgarbage-collection

How to subscribe to an event without preventing garbage collection?


Let's say AppConfiguration.Instance is a singleton.

Now let's say my UI dynamically adds a button that should change it's text if the configuration is changed, so my app could do:

AppConfiguration.Instance.Changed += Changed_Handler;

On the button's code, but I don't wanna do that because that will prevent garbage collecion of the button after the user navigates to another screen and the button gets removed from the form

My question is: Is there a design pattern for listening to an event without preventing garbage collection asides from manually unsubscribing to the event with AppConfiguration.Instance.Changed -= Changed_Handler;?


Solution

  • After writing the and question and doing my last search-before-posting on weak bindings I came across the weak event pattern that does exactly what I want