简体   繁体   English

在Web应用程序中托管powershell运行空间

[英]Hosting powershell runspace in web application

I'm writing a web service that executes powershell scripts (active directory, directory management, etc). 我正在编写一个执行powershell脚本的Web服务(活动目录,目录管理等)。

Right now, Runspace instance is created per web request. 现在,每个Web请求都会创建Runspace实例。 As Runspace initialization is time consuming operation, plus often I have to import modules, like ActiveDirectory, which are also slow operations. 由于Runspace初始化是一项耗时的操作,因此通常我必须导入像ActiveDirectory这样的模块,这些模块的运行速度也很慢。

In this blog post Managing Exchange 2007 Recipients with C# , the Runspace instance is kept in a static field. 在此博客文章“ 使用C#管理Exchange 2007收件人”中 ,Runspace实例保留在静态字段中。

I wander what if I keep Runspace instance in static field, would it be thread safe? 如果我将Runspace实例保存在静态字段中,我会徘徊,它是否是线程安全的? Maybe there are other drawbacks of doing it this way? 这样做可能有其他缺点吗?

Thanks 谢谢

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. 我建议你创建一个RunspacePool并让你的web服务队列工作。 This is actually pretty easy to do. 这实际上很容易做到。 I blogged about it for v2 ctp3, but the API has not changed for RTM. 我在v2 ctp3上发表过关于它的博客,但是RTM没有改变API。

http://www.nivot.org/2009/01/22/CTP3TheRunspaceFactoryAndPowerShellAccelerators.aspx 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. 如果要使用一个或多个模块预加载池中的每个运行空间,请使用RunspaceFactory.CreateRunspacePool(InitialSessionState)重载。 To see how to create and initialize this, see: 要了解如何创建和初始化它,请参阅:

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

Every time you create a PowerShell instance, assign the pool to its RunspacePool property. 每次创建PowerShell实例时,都将池分配给其RunspacePool属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM