views:

694

answers:

2

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).

+3  A: 

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.)

EDIT changed destructor to finalizer, I'm showing my C++ background again.

Eloff
The name is "finializer", it is perhaps unfortunate that C# uses similar syntax as a C++ destructor.
Dan
Right, getting my languages confused here.
Eloff
It is to be noted that the default *Finalizer* does nothing. See also: http://stackoverflow.com/questions/898828/c-finalize-dispose-pattern/898867#898867
Wernight
A: 

The garbage collector calls the Finalizer; That is:

public class Test : IDisposable
{
    ~Test()
    {
        // Do finalization
    }
}

I'd highly recommend that you use the standard Dispose Pattern. Other questions such as this one might help.

Bryan Menard
Your code sample is misleading as it seems to imply that implementing IDisposable is needed have a finalizer (although I agree that's best practices).
Trillian
@Trillian - a finalizer is **not** best practice in most cases. See for instance the code comments at http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx
TrueWill
@Zxpro IDisposable attempts to add a deterministic dispose path; Finalizers in C# -- and most "managed" languages -- are generally undeterministic in when (or even if) they fire and thus do not fit the same scope. However "best practices" generally have finalizers provide an "uh oh!" guard (simply calling Dispose(false) here) to clean up external resources.
pst
This is not an attempt to discuss best practices. There's a ton of questions on SO on that topic. I was simply answering the OP's question (What does the GC calls?) As a side note, the Finalizer *is* part of the best-practices concerning the Dispose Pattern.
Bryan Menard