开发者

Lambda Expressions and Event Subscriptions

I've heard that if lambda expressions are used to subscribe to an开发者_如何学C 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;
                        }
                    };


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜