Powershell如何实现工作线程
问题描述:
我的脚本中有一个性能问题,因此我想实现某种工作人员主题.但是到目前为止,我还没有找到解决方案.
I have a little performance issue in my script, so i would like to implement some sort of worker theads. but so far i have not been able to find a solution..
我希望的是这样的:
- 启动工作线程池-这些线程从队列中获取命令"并对其进行处理
- 主脚本在运行时会将命令"写入队列
- 一旦完成,主程序就会告诉每个线程停止
- main将在退出之前等待所有工作人员结束.
有人知道如何做到这一点吗?
does anybody have en idea on how to do this?
答
在基思·希尔(Keith Hill)的指针的帮助下-我使它工作了-非常感谢...
With some help from the pointers made by Keith hill - i got it working - thanks a bunch...
这是我的概念证明的代码片段:
Here is a snipping of the code that did my prove of concept:
function New-Task([int]$Index,[scriptblock]$ScriptBlock) {
$ps = [Management.Automation.PowerShell]::Create()
$res = New-Object PSObject -Property @{
Index = $Index
Powershell = $ps
StartTime = Get-Date
Busy = $true
Data = $null
async = $null
}
[Void] $ps.AddScript($ScriptBlock)
[Void] $ps.AddParameter("TaskInfo",$Res)
$res.async = $ps.BeginInvoke()
$res
}
$ScriptBlock = {
param([Object]$TaskInfo)
$TaskInfo.Busy = $false
Start-Sleep -Seconds 1
$TaskInfo.Data = "test $($TaskInfo.Data)"
}
$a = New-Task -Index 1 -ScriptBlock $ScriptBlock
$a.Data = "i was here"
Start-Sleep -Seconds 5
$a
这是证明数据已传递到线程中并再次返回的结果:
And here is the result proving that the data was communicated into the thread and back again:
Data : test i was here
Busy : False
Powershell : System.Management.Automation.PowerShell
Index : 1
StartTime : 11/25/2013 7:37:07 AM
async : System.Management.Automation.PowerShellAsyncResult
如您所见,$ a.data现在前面有"test"
as you can see the $a.data now have "test" in front
非常感谢...