How does threading in powershell work?

前端 未结 6 1447
有刺的猬
有刺的猬 2020-12-23 23:14

I want to parallelize some file-parsing actions with network activity in powershell. Quick google for it, start-thread looked like a solution, but:

T

6条回答
  •  借酒劲吻你
    2020-12-23 23:28

    Powershell does not have a built-in command named Start-Thread.

    V2.0 does, however, have PowerShell jobs, which can run in the background, and can be considered the equivalent of a thread. You have the following commands at your disposal for working with jobs:

    Name                              Category  Synopsis
    ----                              --------  --------
    Start-Job                         Cmdlet    Starts a Windows PowerShell background job.
    Get-Job                           Cmdlet    Gets Windows PowerShell background jobs that are running in the current ...
    Receive-Job                       Cmdlet    Gets the results of the Windows PowerShell background jobs in the curren...
    Stop-Job                          Cmdlet    Stops a Windows PowerShell background job.
    Wait-Job                          Cmdlet    Suppresses the command prompt until one or all of the Windows PowerShell...
    Remove-Job                        Cmdlet    Deletes a Windows PowerShell background job.
    

    Here is an example on how to work with it. To start a job, use start-job and pass a script block which contains the code you want run asynchronously:

    $job  = start-job { get-childitem . -recurse }
    

    This command will start a job, that gets all children under the current directory recursively, and you will be returned to the command line immediately.

    You can examine the $job variable to see if the job has finished, etc. If you want to wait for a job to finish, use:

    wait-job $job
    

    Finally, to receive the results from a job, use:

    receive-job $job
    

提交回复
热议问题