Trevor Sullivan's Tech Room

Minding the gap between administration and development

PowerShell Quick Tip: Determine STA Threading Mode

Posted by Trevor Sullivan on 2010/11/02


Some code in PowerShell requires you to use the Single-Threaded Apartment (STA) threading model. The PowerShell version 2.0 console host uses Multi-Threaded Apartment by default. The PowerShell Integrated Scripting Environment (ISE) uses the STA threading model.

If you’re writing code using the WPK module included in the PowerShellPack, you will need to ensure that you are using the STA model. You can avoid errors in your code by adding a check for the threading model before you attempt to run WPK code. Here is a simple, one-line example of how to do that:

[System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.ApartmentState -eq [Threading.ApartmentState]::STA

What the above code does is:

  1. Gets the current (default) Runspace
  2. Looks at the ApartmentState property, whose value is an ApartmentState
  3. Compares it to the STA

Note: It’s important to note that, in testing, I discovered that when the threading state is set to MTA in the PowerShell console host, the Runspace.ApartmentState property is set to [Threading.ApartmentState]::Unknown. I don’t know why this is, but keep it in mind if you’re planning on performing a comparison against [Threading.ApartmentState]::MTA – this simply won’t work for the MTA model in PowerShell, unless someone else has a different experience than me.

Advertisements

One Response to “PowerShell Quick Tip: Determine STA Threading Mode”

  1. Shay Levy said

    Here’s a tip from Bruce Payette to get around the issue of [Threading.ApartmentState]::Unknown.

    You can always ask the CLR directly, this will work, regardless of the version of powershell.

    [threading.thread]::CurrentThread.GetApartmentState() -eq ‘STA’

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: