locked
Dispose pattern usage RRS feed

  • Question

  • Hi,

    I was just thinking loud on the fact that what is the correct usage of dispose patter. Reason being, I have seen many codes where people write cleanup code/other code in dispose method, whereas dispose pattern is ideally built for cleaning up ONLY unmanaged resources.

    Have a look at followings. There is nothing wrong as such in the code for returning me operation elapsed time.

    Is it OK to use dispose pattern in such cases OR it is not something it is not meant to be and should restrict only for cleaning unmanaged resources? As a dev, am I recommended to do this?

    class Program
        {
            static void Main(string[] args)
            {
                using (var timer = new MyTimer())
                {
                    // Some operation
                }
                Console.ReadLine();
            }
        }
    
        class MyTimer : IDisposable
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            public MyTimer()
            {
                sw.Start();
            }
            public void Dispose()
            {
                Console.WriteLine("Operation completed in " + sw.Elapsed);
            }
        }
    

    Friday, November 21, 2014 6:56 AM