开发者

How to reuse Get-VMMServer connection?

开发者 https://www.devze.com 2023-04-01 14:30 出处:网络
I am writing a C# application whose Main() will start multiple threads, each thread firing Get-VM commandlet. I am using RunspacePool for this.

I am writing a C# application whose Main() will start multiple threads, each thread firing Get-VM commandlet. I am using RunspacePool for this.

Currently each thread has to first fire Get-VMMServer and then Get-VM. Get-VMMServer takes around 5-6 seconds giving a significant performance hit. Below is the code snippet:

    static void Main()
    {
        InitialSessionState iss = InitialSessionState.CreateDefault();
        PSSnapInException warning;

        iss.ImportPSSnapIn("Microsoft.SystemCenter.VirtualMachineManager", out warning);

        RunspacePool rsp = RunspaceFactory.Crea开发者_开发知识库teRunspacePool(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 connects to a Virtual Machine Manager server (if a connection does not already exist) and retrieves the object that represents this server from the Virtual Machine Manager database.

I want this connection to be reused by each threads.

How can I achieve this? Is there a way to create this connection already in the Main() so that all the Runspaces in the pool can use it?


You could try making the connection to VMM Server a singleton and having every thread use that...

0

精彩评论

暂无评论...
验证码 换一张
取 消