Is there a lock statement in Powershell

When using threads in Powershell, we can use the "lock" operator, as in C #? Or we need to use a code that "locks" gets precompiled, i.e. use the Monitor class?

+4
source share
1 answer

There is no built-in statement in PowerShell lock, but you can acquire \ release an exclusive lock for a specified object using the Monitor Class . It can be used to transfer data between threads when working with Runspaces, as shown in the David Wyatt Thread Synchronization blog post (in PowerShell?) .

Quote:

MSDN ICollection.IsSynchronized Property , SyncRoot - , .

:

# 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)
    }
}

Lock-Object , .

+3

Source: https://habr.com/ru/post/1526475/


All Articles