From 1cdbf46c9ecabe5d2cbb5197cacc01c3cd1179f2 Mon Sep 17 00:00:00 2001 From: Andy Jordan <2226434+andyleejordan@users.noreply.github.com> Date: Thu, 28 Aug 2025 14:21:42 -0700 Subject: [PATCH] Fix `IsMutexPresent()` to avoid incorrect use of `GetLastWin32Error()` (#4910) --- PSReadLine/PlatformWindows.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/PSReadLine/PlatformWindows.cs b/PSReadLine/PlatformWindows.cs index 32cf653..2bf72eb 100644 --- a/PSReadLine/PlatformWindows.cs +++ b/PSReadLine/PlatformWindows.cs @@ -8,6 +8,7 @@ using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; +using System.Threading; using Microsoft.PowerShell; using Microsoft.PowerShell.Internal; using Microsoft.Win32.SafeHandles; @@ -79,19 +80,18 @@ static class PlatformWindows [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr GetStdHandle(uint handleId); - internal const int ERROR_ALREADY_EXISTS = 0xB7; - internal static bool IsMutexPresent(string name) { try { - using var mutex = new System.Threading.Mutex(false, name); - return Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS; - } - catch - { - return false; + if (Mutex.TryOpenExisting(name, out var tempMutex)) + { + tempMutex.Dispose(); + return true; + } } + catch { } + return false; } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]