Powershell Mutex not working as expected


This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 7 months, 1 week ago.

  • Author
  • #54280
    Profile photo of Steve Flowers
    Steve Flowers

    Hello all,

    I am attempting to work with mutexes in Powershell for inter-process synchronization.

    Say I open one PS ISE and perform the below:

    $mutex = New-Object -TypeName system.threading.mutex($true, "TestMutex")

    Then if I open a new ISE tab or a new console session and issue the below:

    $mutex = New-Object -TypeName system.threading.mutex($true, "TestMutex")

    No error is thrown. I would expect an error since a mutex by this name should already exist. Furthermore, the below does not return the mutex like I would expect (when run on the new console):


    And finally, if I performed the below, I would expect a return code of "False" as the mutex should be busy. But I always get "True" (again, on the new console session):

    $mutex = New-Object -TypeName system.threading.mutex($false, "TestMutex")
    if ($mutex.WaitOne(5000)) { write-output "free" }
    else {write-output "mutex busy"}

    Any help would be appreciated.

    • This topic was modified 7 months, 1 week ago by Profile photo of Steve Flowers Steve Flowers.
  • #54282
    Profile photo of Don Jones
    Don Jones

    We'll see if anyone pops in with an answer, but you're a bit outside the PowerShell-verse, here. StackOverflow might be a better spot to ask. Unfortunately, I know practically nothing about .NET's implementation of mutexes to tell you if this is a problem related to PowerShell being essentially single-threaded, with its scope, the fact that PowerShell runs in the DLR, or something else entirely.

You must be logged in to reply to this topic.