What happens with event handlers when an object go

2020-04-07 04:05发布

Let's say we have the following setup:

public class ClassA
{
   public event EventHandler SomeEvent;
}

public class ClassB : IDisposable
{
   public void SomeMethod(ClassA value)
   {
      value.SomeEvent += (s, e) => { DoSomething(); };
   }

   void DoSomething() { }

   void Dispose() { }
}

public static class Program
{
   static void Main()
   {
      var a = new ClassA();

      using (var b = new ClassB())
         b.SomeMethod(a);

      // POINT OF QUESTION!!
   }
}

What happens when the event SomeEvent is raised after the "POINT OF QUESTION"?

4条回答
孤傲高冷的网名
2楼-- · 2020-04-07 04:40

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).

查看更多
Anthone
3楼-- · 2020-04-07 04:41

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.

查看更多
beautiful°
4楼-- · 2020-04-07 04:45

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

查看更多
beautiful°
5楼-- · 2020-04-07 04:52

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.

查看更多
登录 后发表回答