zoukankan      html  css  js  c++  java
  • PowerShell-3.多线程

    $start = Get-Date
     
    $task1 = {
         $vUrl = 'http://img.mottoin.com/wp-content/uploads/2016/09/5-25.png'
         $vLocalPath = 'c:/aaa.png'
         Sleep(5)
         Import-Module BitsTransfer
         Start-BitsTransfer "$vUrl" "$vLocalPath"
         Invoke-Item "$vLocalPath"
    }
     
    $task2 = 
    {
     for($i=1;$i -le 20;$i++){
           Sleep(1)
           Write-Host "loop number_task2$i"
        }    
    }
     
    $task3 = {
    for($i=1;$i -le 10;$i++){
           Sleep(1)
           Write-Host "loop number_task3$i"
        }
    }
     
    # 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
     

    测试结果:

    第一个任务可以下载一张图片,并且打开。

    第二个任务可以执行,但是不会在前台输出,但是可以根据退出时间来估算这个任务跑了。

    第三个任务可以执行,并且在控制台界面输出相关结果。

     

  • 相关阅读:
    神盾局第4季
    PAT 1053. Path of Equal Weight (30)
    PAT 1052. Linked List Sorting (25)
    PAT 1051. Pop Sequence (25)
    PAT-1049. Counting Ones (30)
    PAT-1047. Student List for Course (25)
    PAT 1045. Favorite Color Stripe (30)
    每日编程-20170308
    技术博客的第一篇文章
    《C语言》while语句和dowhie语句(7)
  • 原文地址:https://www.cnblogs.com/csnd/p/12062121.html
Copyright © 2011-2022 走看看