[ACCEPTED]-Garbage Collection on one object, C#-garbage-collection
You can force a collection with GC.Collect(). Be 9 very careful using this, since a full collection 8 can take some time. The best-practice is 7 to just let the GC determine when the best 6 time to collect is.
Does the object contain 5 unmanaged resources but does not implement 4 IDisposable? If so, it's a bug.
If it doesn't, it 3 shouldn't matter if it gets released right 2 away, the garbage collector should do the 1 right thing.
If it "owns" anything other than memory, you 10 need to fix the object to use IDisposable. If 9 it's not an object you control this is something 8 worth picking a different vendor over, because 7 it speaks to the core of how well your vendor 6 really understands .Net.
If it does just 5 own memory, even a lot of it, all you have 4 to do is make sure the object goes out of 3 scope. Don't call
GC.Collect() — it's one of those 2 things that if you have to ask, you shouldn't 1 do it.
You can't perform garbage collection on 19 a single object. You could request a garbage 18 collection by calling GC.Collect() but this 17 will effect all objects subject to cleanup. It 16 is also highly discouraged as it can have 15 a negative effect on the performance of 14 later collections.
Also, calling Dispose 13 on an object does not clean up it's memory. It 12 only allows the object to remove references 11 to unmanaged resources. For example, calling 10 Dispose on a StreamWriter closes the stream 9 and releases the Windows file handle. The 8 memory for the object on the managed heap 7 does not get reclaimed until a subsequent 6 garbage collection.
Chris Sells also discussed 5 this on .NET Rocks. I think it was during 4 his first appearance but the subject might 3 have been revisited in later interviews.
This 2 article by Francesco Balena is also a good 1 reference:
When and How to Use Dispose and Finalize in C# http://www.devx.com/dotnet/Article/33167/0/page/1
Garbage collection in .NET is non deterministic, meaning 13 you can't really control when it happens. You 12 can suggest, but that doesn't mean it will 11 listen.
Tells us a little bit more about 10 the object and why you want to do this. We 9 can make some suggestions based off of that. Code 8 always helps. And depending on the object, there 7 might be a Close method or something similar. Maybe 6 the useage is to call that. If there is 5 no Close or Dispose type of method, you 4 probably don't want to rely on that object, as 3 you will probably get memory leaks if in 2 fact it does contain resourses which will 1 need to be released.
If the object goes out of scope and it have 2 no external references it will be collected 1 rather fast (likely on the next collection).
More Related questions