开发者

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

开发者 https://www.devze.com 2023-03-18 09:30 出处:网络
Let\'s say we have the following setup: public class ClassA { pu开发者_如何学Goblic event EventHandler SomeEvent;

Let's say we have the following setup:

public class ClassA
{
   pu开发者_如何学Goblic 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"?


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


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消