views:

56

answers:

2

Is there some way to free all resources used by certain object ?

If not, why wouldn't I use the GC.Collect() method ?

+2  A: 

Types with resources should implement IDisposable, and freeing these resources is done by calling Dispose (or wrapping them in a using statement). GC.Collect is only necessary for badly-written objects that have resources but don't implement IDisposable.

Stephen Cleary
that's the case, unfortunatelly :(
user1112111
But GC.Collect still won't release unmanaged resources that need to be handled in a Dispose pattern.
Tesserex
@Tesserex: That is not completely true. Classes that reference unmanaged resources will typically implement a finalizer. Finalizers will be executed by the garbage collector. Of course, a class with unmanaged resources, but without a finalizer has been designed incorrectly.
Steven
@user1112111: I'd "push" the producers of bad code to fix their code. However, `GC.Collect` is a way to make their bad code work, at least as far as resources are concerned. On the other hand, if they can't even do this right, one must wonder how many other bugs are lurking in their classes...
Stephen Cleary
@Steven: correct, but I was mainly referring to classes that the user is writing here, since we were talking about implementing IDisposable ourselves, so he would have to implement said finalizer.
Tesserex
+2  A: 

It depends on what resources you mean.

If you are simply talking about memory then the GC will indeed handle that for you when there are no longer any references to the object. Calling GC.Collect will prompt the GC to run, but there is never any guarentee of when the GC will run, even if you call GC.Collect as it runs on a separate thread.

If you are talking about unmanaged resources, such as file handles, DB connections and the like then the best way to manage those is to implement the IDispsable interface, and these resources will then be freed by callers of your code calling the Dispose method (or indeed by the GC disposing of your object).

Steve Haigh