Last active
February 11, 2020 22:51
-
-
Save evanricard/3f169c565f5f0d49f98b233104c4de4b to your computer and use it in GitHub Desktop.
IDisposable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Example : IDisposable | |
{ | |
private IntPtr buffer; // неуправляемый буфер памяти | |
private SafeHandle resource; // управляемый ресурс | |
public Example() // конструктор | |
{ | |
this.buffer = ... | |
this.resource = ... | |
} | |
private bool disposed = false; // флаг | |
~Example() // деструктор | |
{ this.Dispose(false); } // высвобождает неуправляемый ресурс (запуск деструктора, если объект не уничтожен до завершения программы) | |
public virtual void Dispose() // высвобождает все ресурсы | |
{ | |
this.Dispose(true); | |
GC.SuppressFinalize(this); // не вызывать метод завершения (предотвратить запуск деструктора) | |
} | |
protected virtual void Dispose(bool disposing) | |
{ | |
lock (this) | |
{ | |
if (!this.disposed) | |
{ | |
this.disposed = true; | |
ReleaseBuffer(buffer); // высвобождение неуправляемого ресурса | |
if (disposing) | |
{ | |
if (resource != null) resource.Dispose(); // высвобождение управляемого ресурса | |
} | |
} | |
} | |
} | |
} | |
//It's a good idea to override the destructor for the derivative class, and it should cause the Overloaded Dispose (false) method to cause. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment