Proper use of the IDisposable interface

后端 未结 19 3274
情深已故
情深已故 2020-11-21 04:05

I know from reading the Microsoft documentation that the \"primary\" use of the IDisposable interface is to clean up unmanaged resources.

To me, \"unman

19条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 04:53

    Scenarios I make use of IDisposable: clean up unmanaged resources, unsubscribe for events, close connections

    The idiom I use for implementing IDisposable (not threadsafe):

    class MyClass : IDisposable {
        // ...
    
        #region IDisposable Members and Helpers
        private bool disposed = false;
    
        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    
        private void Dispose(bool disposing) {
            if (!this.disposed) {
                if (disposing) {
                    // cleanup code goes here
                }
                disposed = true;
            }
        }
    
        ~MyClass() {
            Dispose(false);
        }
        #endregion
    }
    

提交回复
热议问题