diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs index 403dc0ba..010957c9 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs @@ -39,7 +39,26 @@ internal static class HResultExtensions { if (result < 0) { - ThrowHelper.ThrowWin32Exception(result); + // 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); } } else diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs index 6a818106..dff79a89 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs @@ -180,4 +180,25 @@ 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(); + } + } + } }