PowerShell multithreading to perform front and back operation examples _powershell

Source: Internet
Author: User
Tags sleep

The following example runs two background tasks and one foreground task using the PowerShell thread, creates several long-running tasks, and adds the use of Start-sleep to each task command.

Copy Code code as follows:

$start = Get-date

$task 1 = {Start-sleep-seconds 4; Get-service}
$task 2 = {Start-sleep-seconds 5; Get-service}
$task 3 = {Start-sleep-seconds 3; Get-service}

# run 2 in separate threads, 1 in the foreground
$thread 1 = [Powershell]::create ()
$job 1 = $thread 1. Addscript ($task 1). BeginInvoke ()

$thread 2 = [Powershell]::create ()
$job 2 = $thread 2. Addscript ($task 2). BeginInvoke ()

$result 3 = Invoke-command-scriptblock $task 3

do {start-sleep-milliseconds} until ($job 1. Iscompleted-and $job 2. iscompleted)

$result 1 = $thread 1. EndInvoke ($job 1)
$result 2 = $thread 2. EndInvoke ($job 2)

$thread 1. Runspace.close ()
$thread 1. Dispose ()

$thread 2. Runspace.close ()
$thread 2. Dispose ()

$end = Get-date
Write-host-foregroundcolor Red ($end-$start). TotalSeconds

It takes at least 12 seconds to perform these 3 tasks sequentially from Start-sleep. But this script only executes a little more than 5 seconds. The results are saved as $RESULT1, $result 2 and $RESULT3. Compared to a background job, it will be similar when returning large data.

The source of the article: http://www.pstips.net/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.