views:

254

answers:

1

Some background:

In short, standard SharePoint guidance is that COM-backed objects like SPSite and SPWeb should not be used by different threads. This stands in conflict with PowerShell's use of MTA mode by default, verified in the Leak Workarounds post referenced above. One suggested workaround was to try PowerShell 2.0's -STA flag, which seems like it should solve the problem; however, in the comments on his post Zach suggests STA mode is not enough.

This pushes to the edge of my COM knowledge, so I'm hoping someone can help me understand...

  1. Should STA mode be sufficient to keep object access limited to a single thread across PowerShell pipelines?
  2. If not, why?
+2  A: 

Ultimately, -STA mode should be enough provided you are using Powershell 2.0. The reason for this is that in STA mode, the default runspace reuses a single thread for all interactive commands (and scripts too). It's possible that the version of powershell that Zach was looking at in february behaved differently that the current RC/RTM of PowerShell 2.0. It may have used UseNewThread instead of the current default, ReUseThread:

PS> [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace

Events                : System.Management.Automation.PSLocalEventManager
ThreadOptions         : ReuseThread
RunspaceConfiguration : System.Management.Automation.Runspaces.RunspaceConfigForSingleShell
InitialSessionState   :
Version               : 2.0
RunspaceStateInfo     : Opened
RunspaceAvailability  : Busy
ConnectionInfo        :
ApartmentState        : STA
InstanceId            : 8d3bfae1-8b64-433d-9ab9-ce640b15f84f
SessionStateProxy     : System.Management.Automation.Runspaces.SessionStateProxy
Debugger              : System.Management.Automation.Debugger

So in short, you're ok here. The advanced technique he was talking about was most likely how to spin up a new runspace using ReUseThread which is redundant now since that is the default thread option for -STA. You could however use this technique to run on a single thread in MTA mode ;-)

-Oisin

Microsoft PowerShell MVP

x0n
Hard to argue with that - thanks for the detail. I vaguely recalling looking into ThreadOptions at the time, but probably gave up because minor memory leaks in a dev VM don't bother me. :)
dahlbyk