I thought the GC would call Dispose eventually if your program did not but that you should call Dispose() in your program just to make the cleanup deterministic.
However, from my little test program, I don't see Dispose getting called at all....
public class Test : IDisposable
{
static void Main(string[] args)
{
Test s = new Test();
s = null;
GC.Collect();
Console.ReadLine();
}
public Test()
{
Console.WriteLine("Constructor");
}
public void Dispose()
{
Console.WriteLine("Dispose");
}
}
// Output is just "Constructor", I don't get "Dispose" as I would expect. What's up?
EDIT: Yes, I know I should call Dispose() - I do follow the standard pattern when using disposable objects. My question arises because I'm trying to track down a leak in somebody elses code, which is managed C++ (another layer of complexity that would be the good subject of another thread).
Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.
"Dispose is never called by the . NET Framework; you must call it manually" - the using statement calls Dispose internally.
Implement a finalizer to free resources when Dispose is not called. By default, the garbage collector automatically calls an object's finalizer before reclaiming its memory. However, if the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer.
Dispose should call GC. SuppressFinalize so the garbage collector doesn't call the finalizer of the object. To prevent derived types with finalizers from having to reimplement IDisposable and to call it, unsealed types without finalizers should still call GC.
The GC does not call Dispose
, it calls your finalizer (which you should make call Dispose(false)
).
Please look at the related posts on the side or look up the C# best practices for the Dispose pattern (The docs on IDisposable
explain it quite well IIRC.)
Short answer is "no". More detailed answers can be found on my replies to "Is it bad practice to depend on the .NET Garbage Collector" and "What happens if I don't call Dispose()"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With