views:

77

answers:

2

I have a memory leak question. Will the instances of obj ever be eligible for garbage collection until the class instance of TopClass goes out of scope?

public class TopClass
{
  public void MyFunction()
  {
    TestClass obj = new TestClass();
    obj.PropertyChanged += (s,e) => { //Do some code };
    obj = null;
  }
}

Furthermore that would make all objects that instantiate a TopClass and invoke MyFunction() to not be eligible for GC right?

I understand that in managed code once the application goes out of scope then all the objects are eligible, but I want to know WHILE my app is running this will cause a memory leak. Right?

+3  A: 

obj will be eligible to garbage collection as soon as you set it too null (but the actual collection will be done later of course). Subscribing to the PropertyChanged event doesn't create a reference to obj, it creates a reference from obj to the instance of TopClass. And it won't prevent collection of the TopClass instance either, unless it's referenced somewhere else

Thomas Levesque
+3  A: 

Nope. obj will be collected all right. Nothing in this code causes a strong reference.

An object can be kept alive by being attached as an event handler, but an object cannot be kept alive by having event handlers.

zneak
Yes, the TestClass instance can be collected right after (or even during) the call to MyFunction.
Steven