PowerShell: Threading for PowerShell v1.0

Ok, so this solution really isn't threading, but a neat way to get async scripts to run! The important thing to remember is that each "thread" is actually a PowerShell "runspace". Meaning, scripts run within the thread don't have access to objects or functions defined outside the thread. The script is composed of the following commands:

New-Thread: Creates a new instance of a thread
Start-Thread: Invokes an async execution of a script block
Stop-Thread: Stops a thread from running if it is still executing
Read-Thread: Reads all errors and output to the current runspace
Join-Thread: Waits for the thread to complete and reads off the errors and output to the current runspace

A simple example of how to use this is as follows.

$thread = Start-Thread {
    foreach ($i in (1..5)) {
        echo "Sleeping for $i seconds..."
        Start-Sleep $i
    }
}
# ... do some work here or spawn other threads
Join-Thread $thread

I have some other ideas around injecting "variables" and being able to run script blocks within the new "thread" but I'll save that for a later post ...

Attachment: PSThreading.zip
Published Tuesday, April 29, 2008 4:20 PM by adweigert
Filed under: ,

Comments

# PowerShell: Threading Enhancements FTW!

Wednesday, April 30, 2008 9:25 AM by The Technical Adventures of Adam Weigert

To build on the threading library I mentioned here , I've added some functionality to make it easier

# re: PowerShell: Threading for PowerShell v1.0

Monday, May 05, 2008 7:55 PM by Keith Hill

Have you had a look at the new *-PSJob and *-Runspace cmdlets in the V2.0 CTP2 drop?  

# re: PowerShell: Threading for PowerShell v1.0

Tuesday, May 06, 2008 7:58 AM by adweigert

Yes, and I can't wait for RTM! Unfortunately, I needed threading now and couldn't use a CTP in production. :)