c standard idispose pattern usage example

  • 2020-06-12 10:30:38
  • OfStack

IDispose model in C + + by many, is used to clean up resources, and in C #, resources can be divided into two, managed and unmanaged managed resource is made up of C # CLR help us clean up, it is by calling the object to release the object's destructor completed, and for the hosting system, requires us to release, such as database connection object, which requires us to invoke it manually Dispose () method to realize the object of its release, in fact, Dispose () content exactly do what matter, we are not clear, Of course this is object orientation, it doesn't want you to implement the details of the relationship, huh!

For us developers, after understanding how to use it, always interested in how it implement, here, I will put the C # realize IDispose pattern code, everybody to learn 1, in fact, it also a lot of, the use of occasions when we manually on site, the database for encapsulation, used to, see 1 under the code below:


/// <summary>
    ///  implementation IDisposable , the resource recovery of the unmanaged system 
    /// </summary>
    public class IDisplosePattern : IDisposable
    {
        public void Dispose()
        {
            this.Dispose(true);//// Release of managed resources 
            GC.SuppressFinalize(this);// Requests that the system not call the finalizer for the specified object . // This method is set in the object header 1 The bits that the system checks when the finalizer is called 
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!_isDisposed)//_isDisposed for false Indicates that no manual action has been taken dispose
            {
                if (disposing)
                {
                    // Clean up managed resources 
                }
                // Clean up unmanaged resources 
            }
            _isDisposed = true;
        }
        private bool _isDisposed;
        ~IDisplosePattern()
        {
            this.Dispose(false);// Release the unmanaged resource. The managed resource is handled by the finalizer 
        }
    }

Through the code above, we know, for hosting system (C # CLR management for us), directly through ~ IDisplosePattern release () method, and ~ IDisplosePattern () when this method is invoked, we don't know, because it is made of CLR help us call, and we manually dispose method, it calls the dispose (true) the overloaded methods, it will help us to clean up the managed and unmanaged resources.


Related articles: