Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a lock statement in PowerShell

When using threads in PowerShell, are we able to use the lock statement like in C#?

Or do we need to use the code that lock gets pre compiled to, ie. use the Monitor class?

like image 694
David Klempfner Avatar asked Feb 12 '14 06:02

David Klempfner


1 Answers

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.

like image 124
beatcracker Avatar answered Oct 20 '22 03:10

beatcracker