Do you need to dispose of objects and set them to null?

前端 未结 11 1847
不思量自难忘°
不思量自难忘° 2020-11-22 10:58

Do you need to dispose of objects and set them to null, or will the garbage collector clean them up when they go out of scope?

11条回答
  •  太阳男子
    2020-11-22 11:48

    As others have said you definitely want to call Dispose if the class implements IDisposable. I take a fairly rigid position on this. Some might claim that calling Dispose on DataSet, for example, is pointless because they disassembled it and saw that it did not do anything meaningful. But, I think there are fallacies abound in that argument.

    Read this for an interesting debate by respected individuals on the subject. Then read my reasoning here why I think Jeffery Richter is in the wrong camp.

    Now, on to whether or not you should set a reference to null. The answer is no. Let me illustrate my point with the following code.

    public static void Main()
    {
      Object a = new Object();
      Console.WriteLine("object created");
      DoSomething(a);
      Console.WriteLine("object used");
      a = null;
      Console.WriteLine("reference set to null");
    }
    

    So when do you think the object referenced by a is eligible for collection? If you said after the call to a = null then you are wrong. If you said after the Main method completes then you are also wrong. The correct answer is that it is eligible for collection sometime during the call to DoSomething. That is right. It is eligible before the reference is set to null and perhaps even before the call to DoSomething completes. That is because the JIT compiler can recognize when object references are no longer dereferenced even if they are still rooted.

提交回复
热议问题