From 740420ddcdec21fb1cdd9d67aecd25340f3f3b16 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 12 Jul 2021 14:31:52 +0200 Subject: [PATCH] Fixed NativeObject.Dispose() logic for GraphicsDevice instances --- src/ComputeSharp/Graphics/GraphicsDevice.cs | 5 --- .../Graphics/Interop/NativeObject.cs | 37 +++++++++++++------ 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 1a1bbd0f..f11840c8 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -383,11 +383,6 @@ namespace ComputeSharp /// protected override void OnDispose() { - if (DeviceHelper.GetDefaultDeviceLuid() == Luid) - { - return; - } - DeviceHelper.NotifyDisposedDevice(this); this.d3D12Device.Dispose(); diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.cs index fc20600f..6bb2f3ce 100644 --- a/src/ComputeSharp/Graphics/Interop/NativeObject.cs +++ b/src/ComputeSharp/Graphics/Interop/NativeObject.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.CompilerServices; using System.Threading; +using ComputeSharp.Graphics.Helpers; namespace ComputeSharp.Interop { @@ -19,7 +20,10 @@ namespace ComputeSharp.Interop /// ~NativeObject() { - CheckAndDispose(); + if (Interlocked.CompareExchange(ref this.isDisposed, 1, 0) == 0) + { + OnDispose(); + } } /// @@ -32,22 +36,31 @@ namespace ComputeSharp.Interop } /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { - CheckAndDispose(); + // If the current instance is a graphics device, check that the LUID doesn't + // match the one for the default device, which is deliberately never disposed. + // This type check is inlined and then resolved at JIT time if the target instance + // is visible to the compiler. That is, if Dispose() is explicitly called on a + // sealed type that is not GraphicsDevice, this entire path will just be removed. + if (GetType() == typeof(GraphicsDevice) && + DeviceHelper.GetDefaultDeviceLuid() == Unsafe.As(this).Luid) + { + return; + } - GC.SuppressFinalize(this); - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void CheckAndDispose() - { if (Interlocked.CompareExchange(ref this.isDisposed, 1, 0) == 0) { - OnDispose(); + [MethodImpl(MethodImplOptions.NoInlining)] + void DisposeAndSuppressFinalize() + { + OnDispose(); + + GC.SuppressFinalize(this); + } + + DisposeAndSuppressFinalize(); } }