Dispose, when is it called?

Posted by Snake on Stack Overflow See other posts from Stack Overflow or by Snake
Published on 2010-05-20T07:53:28Z Indexed on 2010/05/20 8:00 UTC
Read the original article Hit count: 143

Filed under:
|

Consider the following code:

namespace DisposeTest
{
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Calling Test");

            Test();

            Console.WriteLine("Call to Test done");
        }

        static void Test()
        {
            DisposeImplementation di = new DisposeImplementation();
        }
    }

    internal class DisposeImplementation : IDisposable
    {
        ~DisposeImplementation()
        {
            Console.WriteLine("~ in DisposeImplementation instance called");
        }
        public void Dispose()
        {
            Console.WriteLine("Dispose in DisposeImplementation instance called");
        }
    }
}

The Dispose just never get's called, even if I put a wait loop after the Test(); invocation. So that quite sucks. I want to write a class that is straightforward and very easy to use, to make sure that every possible resource is cleaned up. I don't want to put that responsibilty to the user of my class.

Possible solution: use using, or call Dispose myself(basicly the same). Can I force the user to use a using? Or can I force the dispose to be called?

Calling GC.Collect(); after Test(); doesn't work either.

Putting di to null doesn't invoke Dispose either. The Deconstructor DOES work, so the object get's deconstructed when it exits Test()

© Stack Overflow or respective owner

Related posts about c#

Related posts about net