Is there a lock statement in PowerShell Is there a lock statement in PowerShell multithreading multithreading

Is there a lock statement in PowerShell


There is no native lock statement in PowerShell as such, but you can acquire\release an exclusive lock on a specified object using Monitor Class. It can be used to pass data between threads when working with Runspaces, which is demonstrated in David Wyatt's blog post Thread Synchronization (in PowerShell?).

Quote:

MSDN page for ICollection.IsSynchronized Property mentions that you must explicitly lock the SyncRoot property of an Collection to perform a thread-safe enumeration of its contents, even if you're dealing with a Synchronized collection.

Basic example:

# Create synchronized hashtable for thread communication$SyncHash = [hashtable]::Synchronized(@{Test='Test'})try{    # Lock it    [System.Threading.Monitor]::Enter($SyncHash)    $LockTaken = $true    foreach ($keyValuePair in $SyncHash.GetEnumerator())    {        # Hashtable is locked, do something        $keyValuePair    }}catch{    # Catch exception    throw 'Lock failed!'}finally{    if ($LockTaken)    {        # Release lock        [System.Threading.Monitor]::Exit($SyncHash)    }}

David has also written fully functional Lock-Object module, which implements this approach.