How do i free objects in C#

2020-02-28 03:03发布

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 like to free obj1, 
after it is no longer required 
and also more importantly 
its scope is the full run time of the program.
*/

Thanks for all your help

9条回答
老娘就宠你
2楼-- · 2020-02-28 03:21

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.)

查看更多
欢心
3楼-- · 2020-02-28 03:21

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.

查看更多
混吃等死
4楼-- · 2020-02-28 03:25

You do not. This is what a garbage collector does automatically - basically when the .NET runtime needs memory, it will go around and delete objects that are not longer in use.

What you have to do for this to work is to remove all linnks to the object.

In your case....

obj1=null;

at the end, then the object is no longer referenced and can be claimed from the garbage collector.

You can check http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) for more details.

Note that if the object has references to unmanaged ressources (like open files etc.) it should implement the Disposable pattern (IDisposable interface) and you should explicitely release those references when you dont need the object anymore.

查看更多
登录 后发表回答