The IDispose pattern is used a lot in C++ and is used to clean up resources. In C#, resources are divided into two types: managed and unmanaged. The managed resources are cleaned by the C# CLR. It is the object release work done by calling the object's destructor. For non-managed systems, we need to release it ourselves, such as database connection objects. This requires us to manually call its Dispose() method to realize the release of the object. In fact, we are not sure what the Dispose() content does. Of course, this is object-oriented, and it does not want your relationship implementation details, haha!
For us developers, after understanding how to use it, we will always be interested in how it is implemented. Below, I will show the code that implements the IDispose mode in C#. Let’s learn it together. In fact, it has many usage occasions. When we manually encapsulate the website and database, we will use it. Let’s take a look at the code below:
/// <summary>
/// Implement IDisposable to recycle resources on unmanaged systems
/// </summary>
public class IDisplosePattern : IDisposable
{
public void Dispose()
{
(true);////Release managed resources
(this);//Request the system not to call the specified object's finalizer. //This method sets a bit in the object header, and the system will check this bit when calling the finalizer.
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)//_isDisposed is false, which means that no manual dispose is performed
{
if (disposing)
{
//Cleaning managed resources
}
//Clean unmanaged resources
}
_isDisposed = true;
}
private bool _isDisposed;
~IDisplosePattern()
{
(false);//Release unmanaged resources, and the managed resources are completed by the ultimate device itself
}
}
Through the above code, we know that for the managed system (the CLR of C# is managed for us), we will directly release it through the ~IDisplosePattern() method. We don’t know when the ~IDisplosePattern() method is called, because it is called by the CLR. When we manually perform the dispose method, it will call the overloaded method dispose(true), which will help us clean up managed and unmanaged resources.