How do i free objects in C#

后端 未结 9 1662
傲寒
傲寒 2021-01-01 21:53

Can anyone please tell me how I can free objects in C#? For example, I have an object:

Object obj1 = new Object();
//Some code using obj1
/*
Here I would l         


        
相关标签:
9条回答
  • 2021-01-01 22:30

    You stop referencing them and let the garbage collector take them.

    When you want to free the object, add the following line:

    obj1 = null;

    The the garbage collector if free to delete the object (provided there are no other pointer to the object that keeps it alive.)

    0 讨论(0)
  • 2021-01-01 22:30

    As others have mentioned you don't need to explicitly free them; however something that hasn't been mentioned is that whilst it is true the inbuilt garbage collector will free them for you, there is no guarantee of WHEN the garbage collector will free it.

    All you know is that when it has fallen out of scope it CAN be cleaned up by the GC and at some stage will be.

    0 讨论(0)
  • 2021-01-01 22:36

    You don't have to. You simply stop referencing them, and the garbage collector will (at some point) free them for you.

    You should implement IDisposable on types that utilise unmanaged resources, and wrap any instance that implements IDisposable in a using statement.

    0 讨论(0)
  • 2021-01-01 22:40

    You can use the using statement. After the scope the reference to the object will be removed and garbage collector can collect it at a later time.

    0 讨论(0)
  • 2021-01-01 22:41

    As Chris pointed out C# does most of the garbage collection for you. Instances where you would need to consider garbage collection is with the implementation of the IDisposable interface and when using WeakReference. See http://msdn.microsoft.com/en-us/library/system.idisposable.aspx and http://msdn.microsoft.com/en-us/library/system.idisposable.aspx for more information.

    0 讨论(0)
  • 2021-01-01 22:47

    GC will collect all but unmanaged resources.

    The unmanaged resources should implement IDisposable. If you are using an object that implements IDisposable, then you should either call the object's Dispose() method when it is no longer needed or wrap its instance in a using statement.

    0 讨论(0)
提交回复
热议问题