【发布时间】:2019-10-02 23:20:22
【问题描述】:
我构建了一个文件处理器脚本来将一些文件转换为 json。它可以工作但不够快,所以我正在多线程处理它。我更喜欢使用运行空间池,因为您可以指定最大线程限制,它会一次运行那么多线程并在完成其他线程时添加新工作,非常棒。但是我发现,如果我有 6 个工作线程要完成,使用运行空间大约需要 50 分钟,并使我的计算机保持 40% 的 CPU,而只为每件工作使用 Start-Job 将我的计算机固定在 100 % CPU,工作在 15 分钟内完成。我是否以某种方式错误配置了运行空间池?以下是每个的简化示例
### Using Start-Job ###
$files = C:\temp | Get-Childitem -filter '*.xel' # returns 6 items
foreach ($file in $files) {
#simplified
Start-Job -ScriptBlock { C:\temp\FileProcessor.ps1 -filepath $using:file.fullname }
}
### Using Runspace Pool ###
$files = C:\temp | Get-Childitem -filter '*.xel' # returns 6 items
$Code = {
param ($filepath)
#simplified
C:\temp\FileProcessor.ps1 -filepath $filepath
}
$rsPool = [runspacefactory]::CreateRunspacePool(1,100)
$rsPool.Open()
$threads = @()
foreach ($file in $files) {
$PSinstance = [powershell]::Create().AddScript($Code).AddArgument($file.FullName)
$PSinstance.RunspacePool = $rsPool
$threads += $PSinstance.BeginInvoke()
}
while ($threads.IsCompleted -contains $False) {}
$rsPool.Dispose()
与作业相比,我也可能会误解运行空间,欢迎提供任何帮助。谢谢!
【问题讨论】: