PowerShell多线程执行前后台作业的例子
2018-10-12 14:10
871 查看
下面例子使用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 = [PowerShell]::Create()
$job1 = $thread1.AddScript($task1).BeginInvoke()
$thread2 = [PowerShell]::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/
您可能感兴趣的文章:
相关文章推荐
- 31. PowerShell -- 多线程执行前后台作业
- 简单的多线程创建,执行,挂起,终止的例子
- Powershell后台作业、异步操作实例
- LINUX使用nohup命令后台执行提交作业
- Java-多个多线程求和例子以及各种方式的执行效率对比
- 一个例子玩转linux多线程问题(创建 执行 条件变量 ......)
- .Net最简单的创建多线程主线程等待所有线程执行完成的例子
- 如何在web页面中,实现耗时操作的后台执行?多线程吗?
- 一个例子玩转linux多线程问题(创建 执行 条件变量 ......)
- 关于异步更新UI界面多线程执行后台操作的一些思路整理
- shell作业后台执行的方法
- ABC线程如何保证顺序执行 关于多线程的一个小例子
- 简单快速实现使用线程后台执行作业的方法
- Powershell检查网站响应并计算执行时间例子
- 一个例子玩转linux多线程问题(创建 执行 条件变量 ......)
- 后台权限数据表和linux后台执行脚本命令例子
- shell 里执行sql 例子
- jquery ajax后台执行成功却执行error回调函数
- linux线程退出时执行的程序(线程清理处理程序)简单例子
- 后台执行UNIX/Linux命令和脚本的五种方法