9

I'm writing a web service that executes powershell scripts (active directory, directory management, etc).

Right now, Runspace instance is created per web request. As Runspace initialization is time consuming operation, plus often I have to import modules, like ActiveDirectory, which are also slow operations.

In this blog post Managing Exchange 2007 Recipients with C# , the Runspace instance is kept in a static field.

I wander what if I keep Runspace instance in static field, would it be thread safe? Maybe there are other drawbacks of doing it this way?

Thanks

Charles
  • 48,924
  • 13
  • 96
  • 136
Misha N.
  • 3,435
  • 1
  • 26
  • 35

1 Answers1

12

Runspaces are not thread-safe, nor can they guarantee that the scripts they are running are either.

I would suggest you create a RunspacePool and have your web service queue work to it. This is actually pretty easy to do. I blogged about it for v2 ctp3, but the API has not changed for RTM.

http://www.nivot.org/2009/01/22/CTP3TheRunspaceFactoryAndPowerShellAccelerators.aspx

update:

If you want to preload each runspace in the pool with one or more modules, use the RunspaceFactory.CreateRunspacePool(InitialSessionState) overload. To see how to create and initialize this, see:

http://www.nivot.org/2010/05/03/PowerShell20DeveloperEssentials1InitializingARunspaceWithAModule.aspx

Every time you create a PowerShell instance, assign the pool to its RunspacePool property.

Tim Cooper
  • 144,163
  • 35
  • 302
  • 261
x0n
  • 47,695
  • 5
  • 84
  • 110
  • Aha, great! So I should create static field RunspacePool and then pass it to every Powershell instance executed in every web request. Is there a way to preload modules to Runspaces in the pool? Maybe I don't even need to do that? – Misha N. Feb 11 '11 at 19:14
  • tnx, x0n. I wish I could give you two upvotes to this answer :) – Misha N. Feb 11 '11 at 21:19
  • np - btw, I fixed a typo. you assign the pool the powershell's runspacepool property, not runspace (but you would have spotted that pretty quickly.) – x0n Feb 11 '11 at 21:24