在观察者中使用弱引用是个好主意吗?
我已经实现了一个 Observable 类,它存储所有观察者的列表。该列表是否应该包含对观察者的弱引用以防止内存泄漏?
什么是常见做法?
I have implemented an Observable class that stores a list all the observers. Should this list contain weak references to the observers for preventing memory leaks?
What is common practise?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不一定,要看语境。一些观察者可能只想做一些简单的事情,比如日志记录等,并且更愿意通过 Observable 对象保持活动状态。最好的办法就是清楚地记录您的选择,以便观察者知道他们是否需要明确注销自己。
Not necessarily, it depends on the context. Some observers may just want to do simple things like logging and such, and would prefer to be kept alive by the Observable object. Best thing to do is just to clearly document your choice, so that observers know whether or not they need to explicitly deregister themselves.
题外话,如果您使用 Rx 而不仅仅是 .NET 4 中的 IObservable 接口,则应该将 Subscribe 调用映射到 Subject< 的私有实例/code> 因为它将为您处理线程安全和调用顺序。然后,您可以在主题实例上调用
On*
。就主题而言,订阅者通常管理自己的订阅。至少,这意味着处理
Subscribe
返回值,但在 Rx 中,订阅通常会被另一个运算符终止(例如Take
或TakeUntil
)。Off topic, if you are using Rx and not just the
IObservable
interface from .NET 4, you should map theSubscribe
calls through to a private instance ofSubject
as it will handle thread safety and call order for you. You can then callOn*
on the subject instance.On topic, it's typical that subscribers manage their own subscription. In the least this means disposing the
Subscribe
return value, but in Rx then subscription will usually be terminated by another operator (such asTake
orTakeUntil
).