diff --git a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs
index 395624e0..e94a1e95 100644
--- a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs
+++ b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs
@@ -1,4 +1,5 @@
using System;
+using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
@@ -8,6 +9,7 @@ namespace ComputeSharp.Benchmark.Blas;
/// A that benchmarks the shader dispatch times.
///
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
+[MemoryDiagnoser]
public partial class DispatchingBenchmark : IDisposable
{
///
@@ -53,6 +55,18 @@ public partial class DispatchingBenchmark : IDisposable
context.For(64, new TestShader(Buffer!));
}
+ ///
+ /// Invokes a single shader through a compute context, asynchronously.
+ ///
+ [Benchmark]
+ [BenchmarkCategory("SINGLE")]
+ public async Task Compute_Single_WithContext_Async()
+ {
+ await using var context = GraphicsDevice.Default.CreateComputeContext();
+
+ context.For(64, new TestShader(Buffer!));
+ }
+
///
/// Invokes two empty compute shaders one by one.
///
@@ -78,6 +92,20 @@ public partial class DispatchingBenchmark : IDisposable
context.For(64, new TestShader(Buffer!));
}
+ ///
+ /// Invokes two empty compute shaders in a batch, asynchronously.
+ ///
+ [Benchmark]
+ [BenchmarkCategory("MULTIPLE")]
+ public async Task Compute_Multiple_WithContext_Async()
+ {
+ await using var context = GraphicsDevice.Default.CreateComputeContext();
+
+ context.For(64, new TestShader(Buffer!));
+ context.Barrier(Buffer!);
+ context.For(64, new TestShader(Buffer!));
+ }
+
[AutoConstructor]
internal readonly partial struct TestShader : IComputeShader
{
diff --git a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems
index 3d8e7be8..330d197f 100644
--- a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems
+++ b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems
@@ -11,6 +11,7 @@
+
diff --git a/src/ComputeSharp.NetStandard/System/Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/src/ComputeSharp.NetStandard/System/Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs
new file mode 100644
index 00000000..5659d922
--- /dev/null
+++ b/src/ComputeSharp.NetStandard/System/Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs
@@ -0,0 +1,31 @@
+namespace System.Diagnostics.CodeAnalysis;
+
+///
+/// Specifies that the method or property will ensure that the listed field and property members have not-null values.
+///
+[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
+internal sealed class MemberNotNullAttribute : Attribute
+{
+ ///
+ /// Initializes the attribute with a field or property member.
+ ///
+ /// The field or property member that is promised to be not-null.
+ public MemberNotNullAttribute(string member)
+ {
+ Members = new[] { member };
+ }
+
+ ///
+ /// Initializes the attribute with the list of field and property members.
+ ///
+ /// The list of field and property members that are promised to be not-null.
+ public MemberNotNullAttribute(params string[] members)
+ {
+ Members = members;
+ }
+
+ ///
+ /// Gets field or property member names.
+ ///
+ public string[] Members { get; }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj
index 57eb469d..bfbb1376 100644
--- a/src/ComputeSharp/ComputeSharp.csproj
+++ b/src/ComputeSharp/ComputeSharp.csproj
@@ -22,6 +22,7 @@
+
diff --git a/src/ComputeSharp/Graphics/Commands/CommandList.cs b/src/ComputeSharp/Graphics/Commands/CommandList.cs
index e31c9241..61a69232 100644
--- a/src/ComputeSharp/Graphics/Commands/CommandList.cs
+++ b/src/ComputeSharp/Graphics/Commands/CommandList.cs
@@ -1,5 +1,6 @@
using System;
using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE;
@@ -9,7 +10,7 @@ namespace ComputeSharp.Graphics.Commands;
///
/// A command list to set and execute operations on the GPU.
///
-internal unsafe ref struct CommandList
+internal unsafe struct CommandList : IDisposable
{
///
/// The instance associated with the current command list.
@@ -138,7 +139,18 @@ internal unsafe ref struct CommandList
this.device.ExecuteCommandList(ref this);
}
- ///
+ ///
+ /// Executes the commands in the current commands list, returns a .
+ ///
+ /// The to await for the operations to complete.
+ public ValueTask ExecuteAndWaitForCompletionAsync()
+ {
+ this.d3D12GraphicsCommandList.Get()->Close();
+
+ return this.device.ExecuteCommandListAsync(ref this);
+ }
+
+ ///
public void Dispose()
{
this.d3D12CommandAllocator.Dispose();
diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs
index 8679210c..32465be7 100644
--- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs
+++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs
@@ -110,7 +110,15 @@ public static partial class GraphicsDeviceExtensions
/// // Dispatch shaders here...
/// }
///
- /// All dispatched shaders will be executed as soon as the context goes out of scope.
+ /// All dispatched shaders will be executed as soon as the context goes out of scope.
+ /// Asynchronous execution is also supported, through the interface:
+ ///
+ /// await using (var context = device.CreateComputeContext())
+ /// {
+ /// // Dispatch shaders here, they will be executed asynchronously
+ /// }
+ ///
+ /// Copying or not disposing the instance results in undefined behavior.
///
public static ComputeContext CreateComputeContext(this GraphicsDevice device)
{
diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs
new file mode 100644
index 00000000..4c40fe99
--- /dev/null
+++ b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs
@@ -0,0 +1,324 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Threading.Tasks.Sources;
+using ComputeSharp.Core.Extensions;
+using ComputeSharp.Graphics.Commands;
+using ComputeSharp.Graphics.Commands.Interop;
+using ComputeSharp.Interop;
+using Microsoft.Toolkit.Diagnostics;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE;
+#if !NET6_0_OR_GREATER
+using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute;
+#endif
+
+namespace ComputeSharp;
+
+///
+unsafe partial class GraphicsDevice : NativeObject
+{
+#if !NET6_0_OR_GREATER
+ ///
+ /// A delegate for a callback to pass to .
+ ///
+ /// The input context.
+ /// Whether the wait has timed out.
+ private delegate void WaitForSingleObjectCallbackDelegate(void* pContext, byte timedOut);
+
+ ///
+ /// A cached instance wrapping .
+ ///
+ private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackWrapper = WaitForSingleObjectCallback;
+#endif
+
+ ///
+ /// Executes a given command list and waits for the operation to be completed.
+ ///
+ /// The input to execute.
+ internal void ExecuteCommandList(ref CommandList commandList)
+ {
+ ref readonly ID3D12CommandListPool commandListPool = ref Unsafe.NullRef();
+ ID3D12CommandQueue* d3D12CommandQueue;
+ ID3D12Fence* d3D12Fence;
+ ref ulong d3D12FenceValue = ref Unsafe.NullRef();
+
+ // Get the target command queue, fence and pool for the list type
+ switch (commandList.D3D12CommandListType)
+ {
+ case D3D12_COMMAND_LIST_TYPE_COMPUTE:
+ commandListPool = ref this.computeCommandListPool;
+ d3D12CommandQueue = this.d3D12ComputeCommandQueue;
+ d3D12Fence = this.d3D12ComputeFence;
+ d3D12FenceValue = ref this.nextD3D12ComputeFenceValue;
+ break;
+ case D3D12_COMMAND_LIST_TYPE_COPY:
+ commandListPool = ref this.copyCommandListPool;
+ d3D12CommandQueue = this.d3D12CopyCommandQueue;
+ d3D12Fence = this.d3D12CopyFence;
+ d3D12FenceValue = ref this.nextD3D12CopyFenceValue;
+ break;
+ default: ThrowHelper.ThrowArgumentException(); return;
+ }
+
+ // Execute the command list
+ d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf());
+
+#if NET6_0_OR_GREATER
+ ulong updatedFenceValue = Interlocked.Increment(ref d3D12FenceValue);
+#else
+ ulong updatedFenceValue = (ulong)Interlocked.Increment(ref Unsafe.As(ref d3D12FenceValue));
+#endif
+
+ // Signal to the target fence with the updated value. Note that incrementing the
+ // target fence value to signal must be done after executing the command list.
+ d3D12CommandQueue->Signal(d3D12Fence, updatedFenceValue).Assert();
+
+ // If the fence value hasn't been reached, wait until the operation completes
+ if (updatedFenceValue > d3D12Fence->GetCompletedValue())
+ {
+ d3D12Fence->SetEventOnCompletion(updatedFenceValue, default).Assert();
+ }
+
+ // Return the rented command list and command allocator so that they can be reused
+ commandListPool.Return(commandList.DetachD3D12CommandList(), commandList.DetachD3D12CommandAllocator());
+ }
+
+ ///
+ /// Executes a given command list and returns an awaitable for the operation to be completed.
+ ///
+ /// The input to execute.
+ /// The object representing the operation to wait for.
+ /// This method is only supported for compute operations.
+ internal ValueTask ExecuteCommandListAsync(ref CommandList commandList)
+ {
+ // Execute the command list
+ this.d3D12ComputeCommandQueue.Get()->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf());
+
+#if NET6_0_OR_GREATER
+ ulong updatedFenceValue = Interlocked.Increment(ref this.nextD3D12ComputeFenceValue);
+#else
+ ulong updatedFenceValue = (ulong)Interlocked.Increment(ref Unsafe.As(ref this.nextD3D12ComputeFenceValue));
+#endif
+
+ // Signal to the target fence with the updated value. Note that incrementing the
+ // target fence value to signal must be done after executing the command list.
+ this.d3D12ComputeCommandQueue.Get()->Signal(this.d3D12ComputeFence.Get(), updatedFenceValue).Assert();
+
+ // If the fence value has been reached, complete synchronously
+ if (updatedFenceValue <= this.d3D12ComputeFence.Get()->GetCompletedValue())
+ {
+ // Return the rented command list and command allocator so that they can be reused
+ this.computeCommandListPool.Return(commandList.DetachD3D12CommandList(), commandList.DetachD3D12CommandAllocator());
+
+#if NET6_0_OR_GREATER
+ return ValueTask.CompletedTask;
+#else
+ return new(Task.CompletedTask);
+#endif
+ }
+
+ // Setup the awaitable task
+ return WaitForFenceAsync(
+ updatedFenceValue,
+ this,
+ commandList.DetachD3D12CommandList(),
+ commandList.DetachD3D12CommandAllocator()).AsValueTask();
+ }
+
+ ///
+ /// A context to support .
+ ///
+ private struct CallbackContext
+ {
+ ///
+ /// The wrapping the object to signal completion.
+ ///
+ public GCHandle WaitForFenceValueTaskSourceHandle;
+
+ ///
+ /// The wrapping the instance in use.
+ ///
+ public GCHandle GraphicsDeviceHandle;
+
+ ///
+ /// The used to queue the operations.
+ ///
+ public ID3D12GraphicsCommandList* D3D12GraphicsCommandList;
+
+ ///
+ /// The object backing .
+ ///
+ public ID3D12CommandAllocator* D3D12CommandAllocator;
+
+ ///
+ /// The event handle set when the target fence value is reached.
+ ///
+ public HANDLE EventHandle;
+ }
+
+ ///
+ /// Asynchronously waits for a target fence value to be completed.
+ ///
+ /// The target fence value to wait for.
+ /// The instance executing the operations.
+ /// The used to queue the operations.
+ /// The object backing .
+ /// The object representing the operation to wait for.
+ /// This method is only supported for compute operations.
+ private static WaitForFenceValueTaskSource WaitForFenceAsync(
+ ulong d3D12FenceValue,
+ GraphicsDevice device,
+ ID3D12GraphicsCommandList* d3D12GraphicsCommandList,
+ ID3D12CommandAllocator* d3D12CommandAllocator)
+ {
+ HANDLE eventHandle = Windows.CreateEventW(null, Windows.FALSE, Windows.FALSE, null);
+
+ device.d3D12ComputeFence.Get()->SetEventOnCompletion(d3D12FenceValue, eventHandle).Assert();
+
+ WaitForFenceValueTaskSource waitForFenceValueTaskSource = WaitForFenceValueTaskSource.Rent();
+ CallbackContext* callbackContext = (CallbackContext*)NativeMemory.Alloc((nuint)sizeof(CallbackContext));
+
+ callbackContext->WaitForFenceValueTaskSourceHandle = GCHandle.Alloc(waitForFenceValueTaskSource);
+ callbackContext->GraphicsDeviceHandle = GCHandle.Alloc(device);
+ callbackContext->D3D12GraphicsCommandList = d3D12GraphicsCommandList;
+ callbackContext->D3D12CommandAllocator = d3D12CommandAllocator;
+ callbackContext->EventHandle = eventHandle;
+
+ HANDLE waitHandle;
+
+ _ = Windows.RegisterWaitForSingleObject(
+ phNewWaitObject: &waitHandle,
+ hObject: eventHandle,
+#if NET6_0_OR_GREATER
+ Callback: &WaitForSingleObjectCallback,
+#else
+ Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackWrapper),
+#endif
+ Context: callbackContext,
+ dwMilliseconds: Windows.INFINITE,
+ dwFlags: 0);
+
+ return waitForFenceValueTaskSource;
+ }
+
+ ///
+ /// The callback to signal the completion of a compute pipeline.
+ ///
+ /// The input context.
+ /// Whether the wait has timed out.
+ [UnmanagedCallersOnly]
+ private static void WaitForSingleObjectCallback(void* pContext, byte timedOut)
+ {
+ CallbackContext* callbackContext = (CallbackContext*)pContext;
+
+ WaitForFenceValueTaskSource waitForFenceValueTaskSource = Unsafe.As(callbackContext->WaitForFenceValueTaskSourceHandle.Target)!;
+ GraphicsDevice device = Unsafe.As(callbackContext->GraphicsDeviceHandle.Target)!;
+ ID3D12GraphicsCommandList* d3D12GraphicsCommandList = callbackContext->D3D12GraphicsCommandList;
+ ID3D12CommandAllocator* d3D12CommandAllocator = callbackContext->D3D12CommandAllocator;
+ HANDLE eventHandle = callbackContext->EventHandle;
+
+ callbackContext->WaitForFenceValueTaskSourceHandle.Free();
+ callbackContext->GraphicsDeviceHandle.Free();
+
+ device.computeCommandListPool.Return(d3D12GraphicsCommandList, d3D12CommandAllocator);
+
+ _ = Windows.CloseHandle(eventHandle);
+
+ NativeMemory.Free(callbackContext);
+
+ waitForFenceValueTaskSource.Complete();
+ }
+
+ ///
+ /// A reusable type.
+ ///
+ private sealed class WaitForFenceValueTaskSource : IValueTaskSource
+ {
+ ///
+ /// The shared holding the reusable instances.
+ ///
+ private static readonly ConcurrentQueue ValueTaskSourceQueue = new();
+
+ ///
+ /// The approximate count of currently enqueued instances in .
+ ///
+ private static volatile int queuedValueTaskSourceCount;
+
+ ///
+ /// The wrapped instance being used.
+ ///
+ private ManualResetValueTaskSourceCore