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();