[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[转载代码] [PowerShell每日技巧]高效运行后台任务(20140414)

Using background jobs to run tasks concurrently often is not very efficient as you might have seen in a previous tip. Background job performance worsens with the amount of data that is returned by a background job.

A much more efficient way uses in-process tasks. They run as separate threads inside the very same PowerShell, so there is no need to serialize return values.

Here is a sample that runs two processes in the background, and one in the foreground, using PowerShell threads. To create some really long-running tasks, each task uses Start-Sleep in addition to some other command:
  1. $start = Get-Date
  2. $task1 = { Start-Sleep -Seconds 4; Get-Service }
  3. $task2 = { Start-Sleep -Seconds 5; Get-Service }
  4. $task3 = { Start-Sleep -Seconds 3; Get-Service }
  5. # run 2 in separate threads, 1 in the foreground
  6. $thread1 = [PowerShell]::Create()
  7. $job1 = $thread1.AddScript($task1).BeginInvoke()
  8. $thread2 = [PowerShell]::Create()
  9. $job2 = $thread2.AddScript($task2).BeginInvoke()
  10. $result3 = Invoke-Command -ScriptBlock $task3
  11. do { Start-Sleep -Milliseconds 100 } until ($job1.IsCompleted -and $job2.IsCompleted)
  12. $result1 = $thread1.EndInvoke($job1)
  13. $result2 = $thread2.EndInvoke($job2)
  14. $thread1.Runspace.Close()
  15. $thread1.Dispose()
  16. $thread2.Runspace.Close()
  17. $thread2.Dispose()
  18. $end = Get-Date
  19. Write-Host -ForegroundColor Red ($end - $start).TotalSeconds
复制代码
Running these three tasks consecutively would take at least 12 seconds for the Start-Sleep statements alone. In reality, the script only takes a bit more than 5 seconds. The result can be found in $result1, $result2, and $result3. In contrast to background jobs, there is almost no time penalty for returning large amounts of data.

http://powershell.com/cs/blogs/tips/archive/2014/04/14/running-background-jobs-efficiently.aspx

返回列表