multithreading - PowerShell中是否有lock语句

标签 multithreading powershell locking

在 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/

相关文章:

c - 稍微复杂的线程同步

c++ - 创建自己的线程的 native 共享库可以(应该吗?)支持退出 'without warning' 的使用进程?

包含运算符的 Powershell 脚本不起作用

powershell - 将 stdout 和 stderr 重定向到文件和控制台

powershell - 使用 “invoke-command”捕获命令的返回码-Powershell 2

ruby-on-rails - Rails 如何在不锁定的情况下触摸 Active Record 对象?

c++ - 如何设置pthread_cond_signal 使程序不挂起?

java - UI线程和图像处理

C程序不允许超过n个线程同时执行函数f

java - JAVA中有多少种锁