Board logo

标题: [转载代码] [PowerShell每日技巧]高效运行后台任务(20140414) [打印本页]

作者: DAIC    时间: 2014-4-17 13:19     标题: [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




欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2