benzhou 发表于 2018-9-2 11:46:43

31. PowerShell -- 多线程执行前后台作业

  使用后台作业执行多个任务从先前的技巧中看不是非常高效,它在处理每个后台作业返回结果时将会浪费很多性能。一个更有效的方法是使用进程内的任务。他能分别单独的执行任务与Powershell类似,所以它不是按顺序返回值的。
  下面例子使用Powershell线程运行了两个后台任务和一个前台任务,创建几个运行时间长点的任务,并且每个任务命令中添加使用Start-Sleep。
  代码如下:
  $start = Get-Date
  $task1 = { Start-Sleep -Seconds 4; Get-Service }
  $task2 = { Start-Sleep -Seconds 5; Get-Service }
  $task3 = { Start-Sleep -Seconds 3; Get-Service }
  # run 2 in separate threads, 1 in the foreground
  $thread1 = ::Create()
  $job1 = $thread1.AddScript($task1).BeginInvoke()
  $thread2 = ::Create()
  $job2 = $thread2.AddScript($task2).BeginInvoke()
  $result3 = Invoke-Command -ScriptBlock $task3
  do { Start-Sleep -Milliseconds 100 } until ($job1.IsCompleted -and $job2.IsCompleted)
  $result1 = $thread1.EndInvoke($job1)
  $result2 = $thread2.EndInvoke($job2)
  $thread1.Runspace.Close()
  $thread1.Dispose()
  $thread2.Runspace.Close()
  $thread2.Dispose()
  $end = Get-Date
  Write-Host -ForegroundColor Red ($end - $start).TotalSeconds
  相继执行这3个任务从Start-Sleep中看至少需要花费12秒。但是这个脚本仅执行了5秒多一点。其结果保存为$result1, $result2和$result3。与后台作业对比,它在返回大数据用时将差不多。
  文章出处:http://www.pstips.net/

页: [1]
查看完整版本: 31. PowerShell -- 多线程执行前后台作业