From c8c779d8275cf94b112edca27dc3ddddde8a2664 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 21 Jul 2022 00:29:24 +0200 Subject: [PATCH] Add lock to synchronize Dispose/DeviceLost logic --- .../Graphics/GraphicsDevice.DeviceLost.cs | 15 ++++++++++++++- src/ComputeSharp/Graphics/GraphicsDevice.cs | 14 +++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs index 3bff93f2..931b14cb 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs @@ -61,7 +61,20 @@ unsafe partial class GraphicsDevice return; } - HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason(); + HRESULT result; + + // Make sure to guard against concurrent accesses from the dispose logic + lock (this.d3D12DeviceLock) + { + ID3D12Device* d3D12Device = this.d3D12Device.Get(); + + if (d3D12Device is null) + { + return; + } + + result = d3D12Device->GetDeviceRemovedReason(); + } // Only raise the event once, and store the device removed reason to track it if (result != S.S_OK && diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 66602ebd..031ed041 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -107,6 +107,13 @@ public sealed unsafe partial class GraphicsDevice : NativeObject /// private HRESULT deviceRemovedReason; + /// + /// A lcok object used to synchronize accesses to between and . + /// This is needed because the device lost callback might race with a dispose call and end up trying to invoke a method on an invalid object. + /// We can't just check whether it's , as a null condition might still cause a racing thread to access a freed up object. + /// + private readonly object d3D12DeviceLock = new(); + /// /// Raised whenever the device is lost. /// @@ -402,7 +409,12 @@ public sealed unsafe partial class GraphicsDevice : NativeObject { DeviceHelper.NotifyDisposedDevice(this); - this.d3D12Device.Dispose(); + // Guard the dispose call around the native device to avoid device lost races + lock (this.d3D12DeviceLock) + { + this.d3D12Device.Dispose(); + } + this.d3D12ComputeCommandQueue.Dispose(); this.d3D12CopyCommandQueue.Dispose(); this.d3D12ComputeFence.Dispose();