如何订阅事件不会阻止垃圾回收? [英] How to subscribe to an event without preventing garbage collection?

查看:160
本文介绍了如何订阅事件不会阻止垃圾回收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说, AppConfiguration.Instance 是一个单例。



现在让我们说我的用户界面动态地添加一个按钮,应该改变它的文本配置是否改变,所以我的应用程序可以这样做:

  AppConfiguration.Instance.Changed + = Changed_Handler; 

在该按钮的代码,但我不想这样做,因为这将防止垃圾的收集之后用户键导航到另一个屏幕和按钮会从表单中删除



我的问题是:是否有监听事件不会阻止垃圾收集的旁白设计模式从手动退订事件与 AppConfiguration.Instance.Changed - = Changed_Handler;


解决方案

编写和问题,做我的最后的搜索之前张贴弱绑定后,我穿过的弱事件模式这不正是我想要什么


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 change, 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;?

解决方案

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

这篇关于如何订阅事件不会阻止垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆