diff --git a/src/ComputeSharp.Core/Interop/NativeObject.cs b/src/ComputeSharp.Core/Interop/NativeObject.cs new file mode 100644 index 00000000..b938abb5 --- /dev/null +++ b/src/ComputeSharp.Core/Interop/NativeObject.cs @@ -0,0 +1,52 @@ +using System; + +namespace ComputeSharp.Core.Interop +{ + /// + /// Base class for a class. + /// + public abstract class NativeObject : IDisposable + { + /// + /// Indicates whether or not the current instance has already been disposed. + /// + private bool isDisposed; + + /// + /// Releases unmanaged resources and performs other cleanup operations. + /// + ~NativeObject() + { + CheckAndDispose(false); + } + + /// + /// Releases all the native resources for the current instance. + /// + public void Dispose() + { + GC.SuppressFinalize(this); + + CheckAndDispose(true); + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + private void CheckAndDispose(bool disposing) + { + if (!this.isDisposed) + { + this.isDisposed = true; + + Dispose(disposing); + } + } + + /// + /// Releases unmanaged and (optionally) managed resources. + /// + /// When set to , indicates to dispose managed resources as well. + protected abstract void Dispose(bool disposing); + } +}