Lambda 表达式和事件订阅

发布于 2024-08-11 08:27:19 字数 370 浏览 4 评论 0原文

我听说,如果使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不奢求什么 2024-08-18 08:27:19

不,这是神话。 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.

吃素的狼 2024-08-18 08:27:19

不,在事件订阅的上下文中,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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文