Is there some way to free all resources used by certain object ?
If not, why wouldn't I use the GC.Collect()
method ?
Is there some way to free all resources used by certain object ?
If not, why wouldn't I use the GC.Collect()
method ?
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
.
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).