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:05

It's not recommended, but if you really need to, you can force garbage collection via:

GC.Collect();
查看更多
我只想做你的唯一
3楼-- · 2020-02-28 03:07

You don't have to. The runtime's garbage collector will come along and clean it up for you. That is why you are using C# and not unmanaged C++ in the first place :)

查看更多
▲ chillily
4楼-- · 2020-02-28 03:08

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.

查看更多
太酷不给撩
5楼-- · 2020-02-28 03:09

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.

查看更多
放荡不羁爱自由
6楼-- · 2020-02-28 03:13

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.

查看更多
干净又极端
7楼-- · 2020-02-28 03:18

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.

查看更多
登录 后发表回答