Lambda 表达式和事件订阅
我听说,如果使用 lambda 表达式来订阅事件,则会创建对事件处理程序代码的弱引用,因此当订阅者死亡/不再感兴趣时,不需要显式取消订阅事件。这是真的吗? 例如
aPersion.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "Name")
{
this.Name = this.TheController.Name;
}
};
I've heard that if lambda expressions are used to subscribe to an event, then this creates a weak reference to the event handler code, so it is not required to explicitly unsubscribe from the event when the subscriber dies/is no longer interested. Is this true?
E.g.
aPersion.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "Name")
{
this.Name = this.TheController.Name;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这是神话。 Lambda 创建常规委托(至少在这种用法中)。混淆通常很简单,发布对象是否要在订阅者之前或大约同一时间完成,则无需取消订阅。事件委托仅使订阅者保持活动状态,而不是发布者。
因此,在给出的示例中,这取决于您的发布者:
aPersion
(大概是一个人或类似的人)是否将在表单/页面/任何内容完成后使用 。No, this is myth. Lambdas create regular delegates (in this usage, at least). The confusion is often simply that if the publishing object is going to be finished with before or at around the same time as the subscriber, then there is no need to unsubscribe. The event delegate only keeps the subscriber aliver, not the publisher.
In the example given, therefore, it depends on whether your publisher:
aPersion
(presumably a person or similar) is going to be used after the form/page/whatever has finished.不,在事件订阅的上下文中,lambda 表达式只是所有意图和目的的委托,因此仍然容易出现失效侦听器问题。所以不,它绝对不是一个弱引用。
有多种使用弱引用来解决此问题的方法,这些方法总结得很好在 Damien Guard 的这篇文章中
No, in the context of event subscriptions lambda expressions are just delegates for all intents and purposes and hence remain prone to Lapsed Listener issues. So no, it's definitely not a weak reference.
There are a variety of approaches for using weak references to work around this issue, which are summarised well in this post from Damien Guard