Skip to content

Instantly share code, notes, and snippets.

@AdilHindistan
Created April 12, 2014 02:47
Show Gist options
  • Save AdilHindistan/d56bf34b03f1ddfe4de1 to your computer and use it in GitHub Desktop.
Save AdilHindistan/d56bf34b03f1ddfe4de1 to your computer and use it in GitHub Desktop.
##AH - AdilHindistan - Multi-Threading with PowerShell
Ref: http://bits_video.s3.amazonaws.com/022012-SUPS01_archive.f4v by Tobias Weltner
## Run new thread synchronously
$scriptBlock = {some code here}
$newThread = [Powershell]::Create().AddScript($Code)
$newThread.Invoke() # does not help much, as it stops foreground processing until its job is complete
## Run new thread asynchronously (as if sending a job to the background)
$scriptBlock = {some code here}
$newThread = [Powershell]::Create().AddScript($Code)
$handle = $newThread.BeginInvoke() ##does not wait for code to finish, you just get a handle
while (!$handle.IsCompleted) {
# wait, show-progress, or do something else
}
$newThread.EndInvoke($handle) # Get the job results back
# Cleanup
$newThread.Runspace.Close()
$newThread.Dispose()
## Running (background)a thread in STA mode
$scriptBlock1 = {some code here}
$scriptBlock2 = {some other code here}
$Runspace = [RunSpaceFactory]::CreateRunspace()
$Runspace.ApartmentState= 'STA'
$RunSpace.Open()
$newThread = [PowerShell]::Create()
$newThread.RunSpace= $RunSpace
[void]$newThread.AddScript($ScriptBlock1).AddScript($ScriptBlock2).AddArgument("Some arg").AddArgument("Some other args")
$newThread.Invoke()
## MultiThreading
$scriptBlock = {
}
$throttleLimit = 10 # 10 at a time
$iss = [System.Management.Automation.RunSpaces.InitialSessionState]::CreateDefault()
$pool = [RunSpaceFactory]::CreateRunSpacePool(1,$throttleLimit, $iss, $Host)
$pool.Open()
## Basic, when you need to get results to console, or do something but do not need the data back
For ($i=1; $i -le 100; $i++) {
$newThread = [PowerShell]::Create().AddScript($scriptBlock).AddArgument($i)
$newThread.RunSpacePool = $pool
$handle = $newThread.BeginInvoke()
}
## More useful, you get the handles back so you can do something with the data
$threads = @()
$handles = for ($i=1 ; $i -lt 100; $i++){
$newThread=[PowerShell]::Create().AddScript($scriptBlock).AddArgument($i)
$newThread.RunspacePool = $pool
$newThread.BeginInvoke()
$thread += $newThread
}
## loop while waiting for all threads to complete. Clean up the ones done.
do {
$i = 0
$done = $true
foreach ($handle in $handles){
if ($handle.isCompleted){
$threads[$i].EndInvoke($handle)
$threads[$i].Dispose()
$handles[i] = $null
} else {
$done = $false
}
$i++
}
if (!$done) { start-sleep -sec 1}
} until ($done)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment