Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"?

like image 538
Paulo Santos Avatar asked Jul 05 '11 20:07

Paulo Santos


3 Answers

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

like image 181
Andrey Avatar answered Sep 17 '22 23:09

Andrey


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.

like image 23
IAbstract Avatar answered Sep 21 '22 23:09

IAbstract


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.

like image 23
CodeNaked Avatar answered Sep 19 '22 23:09

CodeNaked