C# 如何重用Get-VMMServer连接?
我正在编写一个C#应用程序,其Main()将启动多个线程,每个线程都会触发Get-VM commandlet。我正在为此使用RunspacePool 当前,每个线程必须首先启动Get-VMMServer,然后再启动Get-VM。Get-VMMServer大约需要5-6秒,会对性能造成显著影响。下面是代码片段:C# 如何重用Get-VMMServer连接?,c#,powershell,hyper-v,C#,Powershell,Hyper V,我正在编写一个C#应用程序,其Main()将启动多个线程,每个线程都会触发Get-VM commandlet。我正在为此使用RunspacePool 当前,每个线程必须首先启动Get-VMMServer,然后再启动Get-VM。Get-VMMServer大约需要5-6秒,会对性能造成显著影响。下面是代码片段: static void Main() { InitialSessionState iss = InitialSessionState.CreateDefau
static void Main()
{
InitialSessionState iss = InitialSessionState.CreateDefault();
PSSnapInException warning;
iss.ImportPSSnapIn("Microsoft.SystemCenter.VirtualMachineManager", out warning);
RunspacePool rsp = RunspaceFactory.CreateRunspacePool(iss);
rsp.Open();
using (rsp)
{
ClassTest n = new ClassTest();
n.intializeConnection(rsp);
Thread t1 = new Thread(new ThreadStart(n.RunScript));
t1.Start();
Thread t2 = new Thread(new ThreadStart(n.RunScript));
t2.Start();
....
}
....
}
class ClassTest
{
RunspacePool rsp;
public void intializeConnection(RunspacePool _rsp)
{
rsp = _rsp;
}
public void RunScript()
{
PowerShell ps = PowerShell.Create();
ps.RunspacePool = rsp;
ps.AddCommand("Get-VMMServer") AddParameter(...); // Doing this in every thread.
ps.AddCommand("Get-VM").AddParameter("Get-VM", "someVM");
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject result in ps.Invoke())
{
...
}
}
}
Get-VMMServer连接到Virtual Machine Manager服务器(如果尚未存在连接),并从Virtual Machine Manager数据库检索表示此服务器的对象
我希望每个线程都能重用此连接
我怎样才能做到这一点?是否有一种方法可以在Main()中创建此连接因此池中的所有运行空间都可以使用它?您可以尝试将到VMM服务器的连接设置为单例,并让每个线程都使用它…您可以尝试将到VMM服务器的连接设置为单例,并让每个线程都使用它…我可以仅使用运行空间运行Get-VMMServer,并且每个线程都有自己的runapce从游泳池里。您建议如何使用singleton让每个线程都使用它?我只能使用运行空间运行Get-VMMServer,每个线程从池中获得自己的RunAPCE。您建议如何使用singleton让每个线程都使用它?