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

ren
  • 3,843
  • 9
  • 50
  • 95

2 Answers2

3

Yes, a can be GC'd in your example. It won't cause any problems either. Think about it.

Class1 a = new Class1();
Class2 b = new Class2();

a.SomeEvent += b.SomeMethod;

In this example, a holds a reference to b, but not the other way round. The a.SomeEvent member is like a List<delegate> (or close to it). It holds references to all the subscribers, so they can be called when needed.

So when a needs to be GC'd, it can be. It will be destroyed, along with the list of subscribers. b will remain happily alive without any problems.

The other way won't work though - b cannot be collected, because a is still holding a reference to it. If it were collected, then a would get a reference to somewhere nonexistant, and the next attempt to raise the event would explode.

Vilx-
  • 104,512
  • 87
  • 279
  • 422
2

By subscribing to an event on an object, you are keeping a reference to the object.

You need to unsubscribe in order to release the reference.

In your case, once Test has finished executing, the reference that a was pointing to will be out of scope and be eligible to garbage collection - having the event subscribed to does not change that.

See my answer on Why can .NET not have memory leaks?.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Don't you mean the other way round? The subscribee has a reference to the subscriber. But if the subscribee can be GC'd and the subscriber can't, it will get GC'd. In other words, in the example given by the OP, `a` can be garbage collected, no problems. – Vilx- Feb 17 '12 at 19:52
  • @Vilx- That's what I wrote. `a` is eligible to garbage collection means it will be garbage collected. – Oded Feb 17 '12 at 19:54
  • I'm sorry, I was confused by the first sentence: "By subscribing to an event on an object, you are keeping a reference to it." I understood it the other way round (b is subscribing to a and keeping a reference to it). – Vilx- Feb 17 '12 at 20:05
  • @Vilx- Fair enough, not the best sentence I ever wrote. – Oded Feb 17 '12 at 20:06