Powershell在完成的脚本中添加多线程 [英] Powershell adding multithreading to finished script
本文介绍了Powershell在完成的脚本中添加多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一个脚本,它工作正常,但是我想通过使用多线程来加快速度.问题是,在不更改大量代码的情况下很难做到这一点.我希望避免使用具有新的单独作用域的作业,但这似乎是不可能的.另外,开始工作真的很慢,它需要~~ 150毫秒才能开始执行.有什么方法可以避免工作,或者至少可以按预期使此脚本块正常工作? (没有双功能,正确传递了参数)
I got a scirpt, that is working fine, but I want to speed up it a little, by using multithreading. The problem is, that it's kinda difficult to do it, without changing a lot of code. I would love to avoid jobs with new separated scopes, but it looks like it's impossible. Also starting-job is really slow, it needs ~~150miliseconds to start execution. Is there any way to avoid jobs, or atleast make this script block work, as expected? (no doubled functions, passing arguments correctly)
Param(
[int]$arg1 = 2, [int]$arg2 = 3
)
$functionDoSomething = {
function doSomething($inp) {
return $inp + 10
}
}
function doSomething($inp) {
return $inp + 10
}
# time: 1523337 ticks
Measure-Command {
Start-Job -Name Job1 -InitializationScript $functionDoSomething -ScriptBlock {
return doSomething ($arg1 + $arg2)
} -ArgumentList $arg1, $arg2
Wait-Job Job1
$var2 = Receive-Job Job1 # result is 10, so arguements aren't passed correctly, trick with @($arg1, arg2) = the same result
}
# time: 6867 ticks
Measure-Command {
$var3 = doSomething ($arg1 + $arg2) # result is 15
}
推荐答案
# Have no fear - Invoke-Parallel is here. Hoping that I can help steer you in the right direction. Let me show you some pseudo code that can point you in the right direction.
# You need a list of objects in which you want to perform an operation for
$listOfComputers = @(
'1'
'2'
'3'
)
# Pipe your array to Invoke-Parallel which takes care of opening threads depending on the amount of objects piped in.
# If you want to control the amount of simultaneous threads simply help Invoke-Parallel -ShowWindow to see how
$results = $listOfComputers | Invoke-Parallel -ScriptBlock {
function doSomething($inp)
{
return [int]$inp + 10
}
if ($_ -eq '1') { Start-Sleep -Seconds 15; Write-Verbose 'Waited 15s' } # Adding this so you can see that this script block is running in a multi-threaded fashion
# $_ refers to the values inside of $listOfComputers
return doSomething ($_)
} -Verbose
$results
<# Notice how 11 comes up last
12
13
11
#>
这篇关于Powershell在完成的脚本中添加多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文