Go to: correctly implement the IDisposable interface and the idisposable Interface
MSDN recommends implementing the IDisposable interface in the following mode:
public class Foo: IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!m_disposed) { if (disposing) { // Release managed resources } // Release unmanaged resources m_disposed = true; } } ~Foo() { Dispose(false); } private bool m_disposed; }View Code
In fact, there are two functions used to release resources in the. NET object: Dispose and Finalize. Finalize is used to release unmanaged resources, while Dispose is used to release all resources, including hosted and unmanaged resources.
In this mode, the void Dispose (bool disposing) function uses a disposing parameter to determine whether the current call is called by Dispose. If it is called by Dispose (), you need to release both hosted and unmanaged resources. If it is ~ Foo () (that is, the Finalize () of C #) is called, you only need to release the unmanaged resources.
This is because the Dispose () function is explicitly called by other code and requires resource release, while Finalize is called by GC. Other Managed Objects referenced by Foo during GC calls may not need to be destroyed, and GC calls the objects even if they are to be destroyed. Therefore, you only need to release unmanaged resources in Finalize. On the other hand, because managed and unmanaged resources have been released in Dispose (), it is unnecessary to call Finalize again when the object is recycled by GC. Therefore, in Dispose (). suppressFinalize (this) prevents repeated calls to Finalize.
However, even if you call Finalize and Dispose repeatedly, the resource is released only once because of the existence of the variable m_disposed. Excessive calls are ignored.
Therefore, the above mode ensures that:
1. Finalize only releases unmanaged resources;
2. Dispose releases managed and unmanaged resources;
3. It is no problem to repeatedly call Finalize and Dispose;
4. Finalize and Dispose share the same resource release policy, so there is no conflict between them.
In C #, this mode needs to be implemented explicitly, where C #'s ~ The Foo () function represents Finalize ().