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

后端 未结 4 1695
我寻月下人不归
我寻月下人不归 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 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.

提交回复
热议问题