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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With