BenchmarkDotNet supports cooperative cancellation, allowing benchmarks to gracefully respond to cancellation requests such as Ctrl+C.
For long-running individual benchmark iterations, you can make your benchmarks cooperatively cancellable by marking a property or field with the [BenchmarkCancellation] attribute:
[!code-csharpIntroCancellationToken.cs]
You can also use a field instead of a property:
public class MyBenchmarks
{
[BenchmarkCancellation]
public CancellationToken CancellationToken;
[Benchmark]
public async Task MyBenchmark()
{
await Task.Delay(100, CancellationToken);
}
}- Attribute Detection: BenchmarkDotNet automatically detects properties or fields marked with
[BenchmarkCancellation] - Automatic Injection: Before running benchmarks, the framework injects the current cancellation token
- Cooperative Checking: Your benchmark code passes the token to async methods or calls
ThrowIfCancellationRequested()
- Pass to async methods: Pass the token to async framework methods that already support cancellation
- Don't swallow cancellation: Let
OperationCanceledExceptionpropagate - Check periodically in tight loops: For CPU-bound loops, check every N iterations to balance responsiveness and overhead
Properties and fields marked with [BenchmarkCancellation] must be:
- Of type
System.Threading.CancellationToken - Public
- For properties: must have a public setter (init-only setters are supported)
Both static and instance members are supported.