Role
The primary purpose of this interface is to release unmanaged resources. When a managed object is no longer being used, the garbage collector automatically frees the memory allocated to the object. However, it is not possible to predict when garbage collection will take place. In addition, the garbage collector is ignorant of unmanaged resources such as window handles or open files and streams.
Check
When running code analysis in Visual Studio, if a class contains a property that implements the IDisposable pattern, it will remind you that the class also needs to implement IDisposable mode, and that implementing IDisposable mode is a fixed pattern. This mode can be more effective in preventing memory leaks, but also in some places more concise writing code, such as the Using keyword is designed for this purpose.
Using keyword
Provides convenient syntax to ensure proper use of IDisposable objects. The following is an example:
using (Font font = new Font("Arial", 10.0f)) {
byte charset = font.GdiCharSet;
}
The Using keyword guarantees that it must be called when it leaves the using scope font.Dispose . So, if the IDisposable variable is used only locally, it is best to wrap it up so as to prevent a memory leak.
Implement IDisposable
MSDN provides a set of standard implementation templates, addresses in this: Ca1063:implement IDisposable correctly, I slightly modified the implementation of their own:
/// <summary>
/// @author Easily
/// </summary>
public class BaseObject : IDisposable {
private bool _enabled = true;
public bool enabled {
get { return _enabled; }
}
public void Dispose() {
if (_enabled) {
Dispose(true);
}
}
private void Dispose(bool value) {
if (_enabled) {
_enabled = false;
Destroy();
if (value) {
GC.SuppressFinalize(this);
}
}
}
virtual protected void Destroy() {
// release managed resource here
}
~BaseObject() {
Dispose(false);
}
}
The resources that need to be freed are Destroy released inside, so the subclass must be rewritten if there are resources that need to be freed Destroy . Destroywill only be called once, and then the enabled property will be set to false , if the child class is calling Async methods during the run, the callback must check the enabled properties.
From for notes (Wiz)
IDisposable interface is implemented correctly in C #