using System; using System.Runtime.CompilerServices; 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(); } /// /// Releases all the native resources for the current instance. /// public void Dispose() { GC.SuppressFinalize(this); CheckAndDispose(); } /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// private void CheckAndDispose() { if (!this.isDisposed) { this.isDisposed = true; OnDispose(); } } /// /// Releases unmanaged and (optionally) managed resources. /// protected abstract void OnDispose(); /// /// Throws an if the current instance has been disposed. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ThrowIfDisposed() { if (this.isDisposed) { // We can't use ThrowHelper here as we only want to invoke ToString if we // are about to throw an exception. The JIT will recognize this pattern // as this method has a single basic block that always throws an exception. void Throw() => throw new ObjectDisposedException(ToString()); Throw(); } } } }