PowerShell-Multi-threaded execution before and after work

Source: Internet
Author: User

Performing multiple tasks with a background job is not very efficient from the previous techniques, and it wastes a lot of performance when it comes to processing each background job's return results. A more efficient approach is to use in-process tasks. His ability to perform separate tasks is similar to PowerShell, so it does not return values sequentially.

The following example uses a PowerShell thread to run two background tasks and a foreground task, create several long-running tasks, and add the use of Start-sleep to each task command.

The code is 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 successively 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 background jobs, it will be similar when returning big data.

Article Source: http://www.pstips.net/

This article comes from the "Ricky's blog" blog, please be sure to keep this source http://57388.blog.51cto.com/47388/1643899

PowerShell-Multi-threaded execution before and after work

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.