Dealing with .NET IDisposable objects

后端 未结 12 896
自闭症患者
自闭症患者 2021-01-30 13:14

I work in C#, and I\'ve been pretty lax about using using blocks to declare objects that implement IDisposable, which you\'re apparently always suppose

12条回答
  •  耶瑟儿~
    2021-01-30 14:05

    I'm not getting the point of your question. Thanks to the garbage collector, memory leaks are close to impossible to occur. However, you need some robust logic.

    I use to create IDisposable classes like this:

    public MyClass: IDisposable
    {
    
        private bool _disposed = false;
    
        //Destructor
        ~MyClass()
        { Dispose(false); }
    
        public void Dispose()
        { Dispose(true); }
    
        private void Dispose(bool disposing)
        {
            if (_disposed) return;
            GC.SuppressFinalize(this);
    
            /* actions to always perform */
    
            if (disposing) { /* actions to be performed when Dispose() is called */ }
    
            _disposed=true;
    }
    

    Now, even if you miss to use using statement, the object will be eventually garbage-collected and proper destruction logic is executed. You may stop threads, end connections, save data, whatever you need (in this example, I unsubscribe from a remote service and perform a remote delete call if needed)

    [Edit] obviously, calling Dispose as soon as possible helps application performance, and is a good practice. But, thanks to my example, if you forget to call Dispose it will be eventually called and the object is cleaned up.

提交回复
热议问题