Thursday, February 21, 2013

create a disposable class c# Best Practices


Salam,

Do not implement IDisposable lightly. Classes that implement IDisposable take longer to free up their memory because they can't be reclaimed by the Garbage collector on one pass. It takes two passes: One to add them to the finalizer queue, the second to finalize them





public class dis : System.IDisposable
    {
        private IntPtr handle;
        private Component component = new Component();
        private bool disposed = false;
        public dis(IntPtr handle)
        {
            this.handle = handle;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    component.Dispose();
                }
                CloseHandle(handle);
                handle = IntPtr.Zero;
            }
            disposed = true;
        }
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);
        ~dis()
        {
            Dispose(false);
        }
    }