开发者

Does this cause a memory leak (in .NET)?

I have a memory leak question. Will the instances of obj ever be eligible for garbage collection until the class ins开发者_高级运维tance 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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜