2

我正在编写一个 C# 应用程序,其 Main() 将启动多个线程,每个线程触发 Get-VM 命令行开关。我为此使用 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() 中创建这个连接,以便池中的所有运行空间都可以使用它?

4

1 回答 1

0

您可以尝试将与 VMM 服务器的连接设为单例,并让每个线程都使用它...

于 2011-08-29T14:15:35.823 回答