In what cases are detaching from events necessary?

后端 未结 3 1357
北荒
北荒 2020-12-25 14:59

I\'m not sure if I\'m entirely clear on the implications of attaching to events in objects.

This is my current understanding, correct or elaborate:

1

3条回答
  •  感情败类
    2020-12-25 15:32

    The relevant case where you have to unsubscribe from an event is like this:

    public class A
    {
        // ...
        public event EventHandler SomethingHappened;
    }
    
    public class B
    {
        private void DoSomething() { /* ... */ } // instance method
    
        private void Attach(A obj)
        {
           obj.SomethingHappened += DoSomething();
        }
    }
    

    In this scenario, when you dispose of a B, there will still be a dangling reference to it from obj's event handler. If you want to reclaim the B's memory, then you need to detach B.DoSomething() from the relevant event handler first.

    You could run into the same thing if the event subscription line looked like this, of course:

    obj.SomethingHappened += someOtherObject.Whatever.DoSomething();
    

    Now it's someOtherObject that's on the hook and can't be garbage collected.

提交回复
热议问题