From 48f240173f695fff628cc282b225c6947d693fdc Mon Sep 17 00:00:00 2001 From: Braeden Fichtner Date: Tue, 27 May 2025 14:54:52 -0400 Subject: [PATCH] Fix #2739: OS check for platform exclusive event --- .../Helpers/DisposeAtProcessTermination.cs | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/BenchmarkDotNet/Helpers/DisposeAtProcessTermination.cs b/src/BenchmarkDotNet/Helpers/DisposeAtProcessTermination.cs index 12aa89a6fa..bc627a4a1b 100644 --- a/src/BenchmarkDotNet/Helpers/DisposeAtProcessTermination.cs +++ b/src/BenchmarkDotNet/Helpers/DisposeAtProcessTermination.cs @@ -1,4 +1,5 @@ -using System; +using BenchmarkDotNet.Detectors; +using System; using System.Runtime.InteropServices; namespace BenchmarkDotNet.Helpers @@ -27,10 +28,18 @@ namespace BenchmarkDotNet.Helpers /// public abstract class DisposeAtProcessTermination : IDisposable { - public DisposeAtProcessTermination() + private static readonly bool ConsoleSupportsCancelKeyPress + = !(OsDetector.IsAndroid() || OsDetector.IsIOS() || OsDetector.IsTvOS() || Portability.RuntimeInformation.IsWasm); + + protected DisposeAtProcessTermination() { - Console.CancelKeyPress += OnCancelKeyPress; AppDomain.CurrentDomain.ProcessExit += OnProcessExit; + if (ConsoleSupportsCancelKeyPress) + { + // Cancel key presses are not supported by .NET or do not exist for these + Console.CancelKeyPress += OnCancelKeyPress; + } + // It does not make sense to include a Finalizer. We do not manage any native resource and: // as we are subscribed to static events, it would never be called. } @@ -50,8 +59,12 @@ private void OnCancelKeyPress(object? sender, ConsoleCancelEventArgs e) public virtual void Dispose() { - Console.CancelKeyPress -= OnCancelKeyPress; AppDomain.CurrentDomain.ProcessExit -= OnProcessExit; + if (ConsoleSupportsCancelKeyPress) + { + // Cancel key presses are not supported by .NET or do not exist for these + Console.CancelKeyPress -= OnCancelKeyPress; + } } } }