diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs
index 1e4f4099..403dc0ba 100644
--- a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs
+++ b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs
@@ -39,26 +39,7 @@ internal static class HResultExtensions
{
if (result < 0)
{
- // This method just throws the exception from the helper below, which includes the
- // additional logic for the device lost events. This structure ensures this method
- // only has a single basic block, so it can be identified as a throw helper and
- // imported properly, which results in better codegen.
- static void RaiseDeviceLostEventsAndThrowWin32Exception(int result)
- {
- throw RaiseDeviceLostEventsAndGetWin32Exception(result);
- }
-
- // Raises all device lost events, if needed, and then creates the Win32Exception to throw.
- // This method is never inlined, which is needed to make handling the throw helper easier.
- [MethodImpl(MethodImplOptions.NoInlining)]
- static Win32Exception RaiseDeviceLostEventsAndGetWin32Exception(int result)
- {
- DeviceHelper.RaiseAllDeviceLostEventsIfNeeded();
-
- return new Win32Exception(result);
- }
-
- RaiseDeviceLostEventsAndThrowWin32Exception(result);
+ ThrowHelper.ThrowWin32Exception(result);
}
}
else
@@ -71,15 +52,11 @@ internal static class HResultExtensions
if (result < 0)
{
- DeviceHelper.RaiseAllDeviceLostEventsIfNeeded();
-
ThrowHelper.ThrowWin32Exception(result);
}
if (hasErrorsOrWarnings)
{
- DeviceHelper.RaiseAllDeviceLostEventsIfNeeded();
-
ThrowHelper.ThrowWin32Exception("Warning or error detected by ID3D12InfoQueue.");
}
}
diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs
new file mode 100644
index 00000000..e5f077f7
--- /dev/null
+++ b/src/ComputeSharp/Graphics/GraphicsDevice.DeviceLost.cs
@@ -0,0 +1,136 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Threading;
+using ComputeSharp.Core.Extensions;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+#if !NET6_0_OR_GREATER
+using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute;
+#endif
+
+namespace ComputeSharp;
+
+///
+unsafe partial class GraphicsDevice
+{
+#if !NET6_0_OR_GREATER
+ ///
+ /// A cached instance wrapping .
+ ///
+ private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper = WaitForSingleObjectCallbackForWaitForFenceAsync;
+#endif
+
+ ///
+ /// Raises the event if needed.
+ ///
+ private void QueueRaiseDeviceLostEventIfNeeded()
+ {
+ if (IsDisposed)
+ {
+ return;
+ }
+
+ // If the current device removed reason is not S_OK, it means the event
+ // has already been raised (but the device will keep reporting that reason).
+ // In that case, do nothing to avoid raising it again while the device is alive.
+ if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK)
+ {
+ return;
+ }
+
+ HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason();
+
+ // Only raise the event once, and store the device removed reason to track it
+ if (result != S.S_OK &&
+ Interlocked.CompareExchange(
+ ref Unsafe.As(ref this.deviceRemovedReason),
+ (int)result,
+ S.S_OK) == S.S_OK)
+ {
+ QueueRaiseDeviceLostEvent();
+ }
+ }
+
+ ///
+ /// Queues the event being raised on the thread pool.
+ ///
+ private void QueueRaiseDeviceLostEvent()
+ {
+ static void RaiseDeviceLostEvent(GraphicsDevice device)
+ {
+ HRESULT result = Volatile.Read(ref Unsafe.As(ref device.deviceRemovedReason));
+
+ DeviceLostReason reason = (int)result switch
+ {
+ DXGI.DXGI_ERROR_DEVICE_HUNG => DeviceLostReason.DeviceHung,
+ DXGI.DXGI_ERROR_DEVICE_REMOVED => DeviceLostReason.DeviceRemoved,
+ DXGI.DXGI_ERROR_DEVICE_RESET => DeviceLostReason.DeviceReset,
+ DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => DeviceLostReason.DriverInternalError,
+ DXGI.DXGI_ERROR_INVALID_CALL => DeviceLostReason.InvalidCall,
+ _ => DeviceLostReason.UnspecifiedError
+ };
+
+ device.DeviceLost?.Invoke(device, reason);
+ }
+
+ ThreadPool.QueueUserWorkItem(static state => RaiseDeviceLostEvent((GraphicsDevice)state!), this);
+ }
+
+ ///
+ /// Registers a callback to notify whenever the current device is lost.
+ ///
+ /// The current instance.
+ /// The resulting used as callback state.
+ /// The resulting device lost event for the callback.
+ private static void RegisterDeviceLostCallback(GraphicsDevice device, out GCHandle deviceHandle, out HANDLE deviceRemovedEvent)
+ {
+ HANDLE eventHandle = Windows.CreateEventW(null, Windows.FALSE, Windows.FALSE, null);
+
+ // Whenever a device is lost, for any reason, all fences are signaled to the highest value.
+ // As such, a fence event with a value of ulong.MaxValue can act as a device lost callback.
+ device.d3D12ComputeFence.Get()->SetEventOnCompletion(ulong.MaxValue, eventHandle).Assert();
+
+ GCHandle handle = deviceHandle = GCHandle.Alloc(device, GCHandleType.Weak);
+ HANDLE waitHandle;
+
+ _ = Windows.RegisterWaitForSingleObject(
+ phNewWaitObject: &waitHandle,
+ hObject: eventHandle,
+#if NET6_0_OR_GREATER
+ Callback: &WaitForSingleObjectCallbackForRegisterDeviceLostCallback,
+#else
+ Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper),
+#endif
+ Context: (void*)(IntPtr)handle,
+ dwMilliseconds: Windows.INFINITE,
+ dwFlags: 0);
+
+ deviceRemovedEvent = waitHandle;
+ }
+
+ ///
+ /// Unregisters a callback setup by .
+ ///
+ /// The current instance.
+ private static void UnregisterDeviceLostCallback(GraphicsDevice device)
+ {
+ _ = Windows.UnregisterWait(device.deviceRemovedEvent);
+ _ = Windows.CloseHandle(device.deviceRemovedEvent);
+
+ device.deviceHandle.Free();
+ }
+
+ ///
+ /// The callback to signal a device lost event.
+ ///
+ /// The input context.
+ /// Whether the wait has timed out.
+ [UnmanagedCallersOnly]
+ private static void WaitForSingleObjectCallbackForRegisterDeviceLostCallback(void* pContext, byte timedOut)
+ {
+ GraphicsDevice device = Unsafe.As(GCHandle.FromIntPtr((IntPtr)pContext).Target!);
+
+ device.QueueRaiseDeviceLostEventIfNeeded();
+ }
+}
diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs
index 6d2a3ac5..8f17e00f 100644
--- a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs
+++ b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs
@@ -31,9 +31,9 @@ unsafe partial class GraphicsDevice
private delegate void WaitForSingleObjectCallbackDelegate(void* pContext, byte timedOut);
///
- /// A cached instance wrapping .
+ /// A cached instance wrapping .
///
- private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackWrapper = WaitForSingleObjectCallback;
+ private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackForWaitForFenceAsyncWrapper = WaitForSingleObjectCallbackForWaitForFenceAsync;
#endif
///
@@ -131,7 +131,7 @@ unsafe partial class GraphicsDevice
}
///
- /// A context to support .
+ /// A context to support .
///
private struct CallbackContext
{
@@ -195,9 +195,9 @@ unsafe partial class GraphicsDevice
phNewWaitObject: &waitHandle,
hObject: eventHandle,
#if NET6_0_OR_GREATER
- Callback: &WaitForSingleObjectCallback,
+ Callback: &WaitForSingleObjectCallbackForWaitForFenceAsync,
#else
- Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackWrapper),
+ Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackForWaitForFenceAsyncWrapper),
#endif
Context: callbackContext,
dwMilliseconds: Windows.INFINITE,
@@ -212,7 +212,7 @@ unsafe partial class GraphicsDevice
/// The input context.
/// Whether the wait has timed out.
[UnmanagedCallersOnly]
- private static void WaitForSingleObjectCallback(void* pContext, byte timedOut)
+ private static void WaitForSingleObjectCallbackForWaitForFenceAsync(void* pContext, byte timedOut)
{
CallbackContext* callbackContext = (CallbackContext*)pContext;
diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs
index 457c1eb6..2abc731f 100644
--- a/src/ComputeSharp/Graphics/GraphicsDevice.cs
+++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs
@@ -1,7 +1,7 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
-using System.Threading;
+using System.Runtime.InteropServices;
using CommunityToolkit.Diagnostics;
using ComputeSharp.Graphics.Commands.Interop;
#if NET6_0_OR_GREATER
@@ -87,6 +87,16 @@ public sealed unsafe partial class GraphicsDevice : NativeObject
private ComPtr pool;
#endif
+ ///
+ /// A weak to the current instance (used to support the device lost callback).
+ ///
+ private GCHandle deviceHandle;
+
+ ///
+ /// The wait event for the device removed.
+ ///
+ private HANDLE deviceRemovedEvent;
+
///
/// The reason the device was removed, if any.
///
@@ -153,6 +163,10 @@ public sealed unsafe partial class GraphicsDevice : NativeObject
this.pool = this.allocator.Get()->CreatePoolForCacheCoherentUMA();
}
#endif
+
+ this.deviceRemovedReason = S.S_OK;
+
+ RegisterDeviceLostCallback(this, out this.deviceHandle, out this.deviceRemovedEvent);
}
///
@@ -373,56 +387,6 @@ public sealed unsafe partial class GraphicsDevice : NativeObject
d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap);
}
- ///
- /// Raises the event if needed.
- ///
- internal void RaiseDeviceLostEventIfNeeded()
- {
- if (IsDisposed)
- {
- return;
- }
-
- // If the current device removed reason is not S_OK, it means the event
- // has already been raised (but the device will keep reporting that reason).
- // In that case, do nothing to avoid raising it again while the device is alive.
- if (Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason)) != S.S_OK)
- {
- return;
- }
-
- HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason();
-
- // Only raise the event once, and store the device removed reason to track it
- if (Interlocked.CompareExchange(
- ref Unsafe.As(ref this.deviceRemovedReason),
- (int)result,
- S.S_OK) == S.S_OK)
- {
- ThreadPool.QueueUserWorkItem(static state => ((GraphicsDevice)state!).RaiseDeviceLostEvent(), this);
- }
- }
-
- ///
- /// Raises the event.
- ///
- private void RaiseDeviceLostEvent()
- {
- HRESULT result = Volatile.Read(ref Unsafe.As(ref this.deviceRemovedReason));
-
- DeviceLostReason reason = (int)result switch
- {
- DXGI.DXGI_ERROR_DEVICE_HUNG => DeviceLostReason.DeviceHung,
- DXGI.DXGI_ERROR_DEVICE_REMOVED => DeviceLostReason.DeviceRemoved,
- DXGI.DXGI_ERROR_DEVICE_RESET => DeviceLostReason.DeviceReset,
- DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => DeviceLostReason.DriverInternalError,
- DXGI.DXGI_ERROR_INVALID_CALL => DeviceLostReason.InvalidCall,
- _ => DeviceLostReason.UnspecifiedError
- };
-
- DeviceLost?.Invoke(this, reason);
- }
-
///
protected override void OnDispose()
{
@@ -440,6 +404,8 @@ public sealed unsafe partial class GraphicsDevice : NativeObject
this.pool.Dispose();
this.allocator.Dispose();
#endif
+
+ UnregisterDeviceLostCallback(this);
}
///
diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs
index 38bc3787..313d92fa 100644
--- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs
+++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs
@@ -180,25 +180,4 @@ partial class DeviceHelper
return hasErrorsOrWarnings;
}
-
- ///
- /// Raises the event if needed, on all existing devices.
- ///
- public static void RaiseAllDeviceLostEventsIfNeeded()
- {
- lock (DevicesCache)
- {
- foreach (GraphicsDevice device in DevicesCache.Values)
- {
- // Check whether the device was lost, and raise the event once. This method will
- // queue the event being raised on a thread pool thread, which is crucial to avoid
- // invoking the handlers while taking a lock on the devices cache. Doing so would
- // lead to issues if a handler tried to synchronously create a new device, which would
- // take the same lock (it's reentrant) and then add the new device to the cache. Then
- // once this method resumed, the collection would be invalid, and the foreach loop
- // would throw an exception on the next iteration. This will prevent that from happening.
- device.RaiseDeviceLostEventIfNeeded();
- }
- }
- }
}
diff --git a/src/ComputeSharp/Graphics/Interop/NativeObject.cs b/src/ComputeSharp/Graphics/Interop/NativeObject.cs
index 28d49e0b..01cab286 100644
--- a/src/ComputeSharp/Graphics/Interop/NativeObject.cs
+++ b/src/ComputeSharp/Graphics/Interop/NativeObject.cs
@@ -72,6 +72,7 @@ public abstract class NativeObject : IDisposable
///
/// Throws an if the current instance has been disposed.
///
+ /// Thrown if the current instance is disposed.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ThrowIfDisposed()
{
@@ -80,9 +81,9 @@ public abstract class NativeObject : IDisposable
// 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());
+ static void Throw(object self) => throw new ObjectDisposedException(self.ToString());
- Throw();
+ Throw(this);
}
}
}
diff --git a/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs b/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs
index edd2d175..eb881c81 100644
--- a/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs
+++ b/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs
@@ -12,6 +12,9 @@ namespace TerraFX.Interop.Windows
[DllImport("kernel32", ExactSpelling = true)]
public static extern BOOL RegisterWaitForSingleObject([NativeTypeName("PHANDLE")] HANDLE* phNewWaitObject, HANDLE hObject, [NativeTypeName("WAITORTIMERCALLBACK")] void* Callback, [NativeTypeName("PVOID")] void* Context, [NativeTypeName("ULONG")] uint dwMilliseconds, [NativeTypeName("ULONG")] uint dwFlags);
+ [DllImport("kernel32", ExactSpelling = true)]
+ public static extern BOOL UnregisterWait(HANDLE WaitHandle);
+
[NativeTypeName("#define INFINITE 0xFFFFFFFF")]
public const uint INFINITE = 0xFFFFFFFF;
}
diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs
index 6f830d1f..49bba493 100644
--- a/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs
+++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceLostTests.cs
@@ -16,7 +16,7 @@ public partial class DeviceLostTests
{
GraphicsDevice graphicsDevice = device.Get();
- bool win32ExceptionThrown = false;
+ //bool win32ExceptionThrown = false;
TaskCompletionSource<(object? Sender, DeviceLostReason Reason)> tcs = new();
// Register the device lost callback
@@ -28,20 +28,12 @@ public partial class DeviceLostTests
using ReadWriteBuffer bufferB = graphicsDevice.AllocateReadWriteBuffer(128);
graphicsDevice.For(128, new ComputeShaderGettingStuck(bufferA, bufferB, 12345678, 87654321, 42));
-
- // The shader above will always hang, but it's not guaranteed that the DirectX runtime will detect
- // the error right when executing that command. As such, we can force it to be detected by running
- // any other command after that. At this point the device is lost, so any operation will fail.
- graphicsDevice.For(128, new ComputeShaderGettingStuck(bufferA, bufferB, 2, 2, 42));
}
catch (Win32Exception)
{
- win32ExceptionThrown = true;
+ // This is not guaranteed to be thrown, but handle it just in case
}
- // The previous shader must hang and cause an exception
- Assert.IsTrue(win32ExceptionThrown);
-
// Wait up to a second for the event to be raised (it's raised asynchronously on a thread pool thread)
await Task.WhenAny(tcs.Task, Task.Delay(1000));