Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage Collection on one object, C#

I need to dispose of an object so it can release everything it owns, but it doesn't implement the IDisposable so I can't use it in a using block. How can I make the garbage collector collect it?

like image 977
Malfist Avatar asked Dec 14 '22 05:12

Malfist


2 Answers

You can force a collection with GC.Collect(). Be very careful using this, since a full collection can take some time. The best-practice is to just let the GC determine when the best time to collect is.

Does the object contain unmanaged resources but does not implement IDisposable? If so, it's a bug.

If it doesn't, it shouldn't matter if it gets released right away, the garbage collector should do the right thing.

like image 187
Michael Avatar answered Jan 02 '23 01:01

Michael


If it "owns" anything other than memory, you need to fix the object to use IDisposable. If it's not an object you control this is something worth picking a different vendor over, because it speaks to the core of how well your vendor really understands .Net.

If it does just own memory, even a lot of it, all you have to do is make sure the object goes out of scope. Don't call GC.Collect() — it's one of those things that if you have to ask, you shouldn't do it.

like image 27
Joel Coehoorn Avatar answered Jan 02 '23 00:01

Joel Coehoorn