Do i have to unsubscribe from anonymous event handlers of local variables?

后端 未结 3 2258
暖寄归人
暖寄归人 2021-02-20 04:34

If I have a code that looks something like this:

public void Foo()
{
    Bar bar = new Bar();

    bar.SomeEvent += (sender, e) =>
    {
        //Do somethin         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-02-20 05:29

    Well, the object bar refers won't be automatically garbage collected immediately... it's just that the bar variable won't prevent it from being garbage collected.

    The event handler won't prevent the instance of Bar from being garbage collected either though - the "normal" problem is that an event handler keeps the subscriber of an event from being garbage collected (if it uses an instance method or captures "this" in an anonymous function). It doesn't usually affect the publisher being garbage collected. Just remember that the publisher needs to keep a reference to all the subscribers - the subscriber doesn't need to remember what it's subscribed to, unless it explicitly wants to unsubscribe or use some other member later.

    Assuming nothing else is keeping your instance of Bar alive, your code should be fine.

提交回复
热议问题