What happens with event handlers when an object goes out of scope?

后端 未结 4 1694
我寻月下人不归
我寻月下人不归 2021-01-19 02:18

Let\'s say we have the following setup:

public class ClassA
{
   public event EventHandler SomeEvent;
}

public class ClassB : IDisposable
{
   public void S         


        
相关标签:
4条回答
  • 2021-01-19 02:55

    You should use the Dispose() method of ClassB to unsubscribe from the ClassA event. You run the risk of classes not being garbage collected which of course leads to potential memory leaks. You should always unsub from events.

    0 讨论(0)
  • 2021-01-19 03:06

    It will call method of disposed object. That's why it is important to unsubscribe. It even can lead to memory leaks.

    0 讨论(0)
  • 2021-01-19 03:13

    Nothing you have above would unhook your event handler. Since both a and b go out of scope at the same time, you'd be safe. Since a and b can both be collected, then a will not keep b alive.

    If you were to raise the ClassA.SomeEvent event after your using statement, then ClassB.DoSomething will be called even though b has been disposed. You would have to explicitly remove the event handler in this case.

    If you were to retain a reference to a somewhere else, then b would be keep alive by a. Again, because the event handler has not been removed.

    0 讨论(0)
  • 2021-01-19 03:20

    Nothing. Runtime doesn't know about Dispose method and call to this method inside using statement do nothing to memory management.

    Garbage collection is all about memory management, but IDisposable (and Finalizer) is about resource management, so you still should think yourself and implement it manually (and propertly, for example unsubscribe in Dispose).

    0 讨论(0)
提交回复
热议问题