gpt4 book ai didi

c# - 如何重用 Get-VMMServer 连接?

转载 作者:太空宇宙 更新时间:2023-11-03 16:41:58 24 4
gpt4 key购买 nike

我正在编写一个 C# 应用程序,其 Main() 将启动多个线程,每个线程都会触发 Get-VM commandlet。我为此使用 RunspacePool。

目前每个线程都必须先触发 Get-VMMServer,然后再触发 Get-VM。 Get-VMMServer 大约需要 5-6 秒,从而显着影响性能。下面是代码片段:

    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 服务器的连接设为单例并让每个线程都使用它...

关于c# - 如何重用 Get-VMMServer 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7229970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com