在 PowerShell 中使用线程时,我们可以使用 lock
像 C# 中的语句?
或者我们需要使用lock
的代码吗?被预编译为,即。使用 Monitor
类(class)?
最佳答案
没有原生lock
PowerShell 中的语句,但您可以使用 Monitor Class 获取\释放指定对象上的独占锁.它可用于在使用运行空间时在线程之间传递数据,这在 David Wyatt 的博客文章 Thread Synchronization (in PowerShell?) 中进行了演示.
引用:
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.
基本示例:
# 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 还编写了功能齐全的 Lock-Object模块,它实现了这种方法。
关于multithreading - PowerShell中是否有lock语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21719999/