public class A
{
public delegate void D();
public event D E;
...
}
class B
{
void Test()
{
A a = new A();
a.E += () => { ... };
a = null;
}
}
Can a be garbage collected when Test() is over or because of event subscription there is still reference to it somewhere?
Yes,
acan be GC’d in your example. It won’t cause any problems either. Think about it.In this example,
aholds a reference tob, but not the other way round. Thea.SomeEventmember is like aList<delegate>(or close to it). It holds references to all the subscribers, so they can be called when needed.So when
aneeds to be GC’d, it can be. It will be destroyed, along with the list of subscribers.bwill remain happily alive without any problems.The other way won’t work though –
bcannot be collected, becauseais still holding a reference to it. If it were collected, thenawould get a reference to somewhere nonexistant, and the next attempt to raise the event would explode.