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"?
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
(andFinalizer
) is about resource management, so you still should think yourself and implement it manually (and propertly, for example unsubscribe inDispose
).Nothing you have above would unhook your event handler. Since both
a
andb
go out of scope at the same time, you'd be safe. Sincea
andb
can both be collected, thena
will not keepb
alive.If you were to raise the
ClassA.SomeEvent
event after your using statement, thenClassB.DoSomething
will be called even thoughb
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, thenb
would be keep alive bya
. Again, because the event handler has not been removed.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.