71

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

noctonura
  • 12,763
  • 10
  • 52
  • 85
  • This question is a duplicate of [http://stackoverflow.com/questions/45036/will-the-garbage-collector-call-idisposable-dispose-for-me](http://stackoverflow.com/questions/45036/will-the-garbage-collector-call-idisposable-dispose-for-me). – Brian Rogers Jan 07 '12 at 20:29

2 Answers2

66

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

Ry-
  • 218,210
  • 55
  • 464
  • 476
Eloff
  • 20,828
  • 17
  • 83
  • 112
  • 1
    Right, getting my languages confused here. – Eloff Nov 07 '09 at 15:53
  • 4
    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 Jun 28 '10 at 08:46
3

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()"

Community
  • 1
  • 1
Dave Black
  • 7,305
  • 2
  • 52
  • 41