知道为什么这个简单的程序(创建PowerShell会话)占用这么多内存(~150 MB)?

时间:2011-11-10 07:22:35

标签: c# .net powershell c#-3.0 powershell-v2.0

我对powershell编程很新。我正在创建远程会话以编程方式执行某些命令。然而,它消耗了如此多的内存(大约150到200 MB)。和更多的会话,更多的内存。

你能帮我解决一下这个问题吗?

  1. 罪魁祸首是什么?
  2. 我该如何解决?
  3. 观察: 1.执行CreateRunSpace命令后,耗费大约3MB。


    有人在创建运行空间时面临同样的问题:

    http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/69ccce9d-4696-4886-a5d0-5d2d2e1e4e6d

    “可能的PowerShell Runspace处理泄漏”

    仍在调查以找到答案......

    删除pssession使得运行空间释放句柄并修复了内存泄漏。它现在在30到40MB之间切换。


    谢谢!

    (仅供参考 - 引用System.Management.Automation.dll)

        using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Management.Automation.Runspaces;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                int success = 0;
                int fails = 0;
                for (int i = 0; i < 50; i++)
                {
                    Runspace rs = RunspaceFactory.CreateRunspace();
                    //After this the memory will be incremented by ~3Mb in taskmanager
                    rs.Open();
                    using (Pipeline pl = rs.CreatePipeline())
                    {
                        Command cmd = new Command("new-pssession");
                        pl.Commands.Add(cmd);
                        var retval = pl.Invoke();
                        if (retval.Count > 0)
                        {
                            success++;
                        }
                        else
                        {
                            fails++;
                        }
                        pl.Stop();
                    }
                    rs.Close();
                    rs = null;
                }
                GC.Collect();
    
            }
    
        }
    }
    

2 个答案:

答案 0 :(得分:3)

看起来像从运行空间中删除pssession释放了内存句柄并修复了泄漏。现在它需要大约35MB。

int success = 0;
int fails = 0;
for (int i = 0; i < 50; i++)
{
    Runspace rs = RunspaceFactory.CreateRunspace();
    rs.Open();
    using (Pipeline pl = rs.CreatePipeline())
    {
        Command cmd = new Command("new-pssession");
        pl.Commands.Add(cmd);
        var retval = pl.Invoke();
        if (retval.Count > 0)
        {
            success++;
            PSSession Session = (PSSession)retval[0].BaseObject;
            using (Pipeline pl2 = rs.CreatePipeline())
            {
                Command cmd2 = new Command("remove-pssession");
                cmd2.Parameters.Add("Id", Session.Id);
                pl2.Commands.Add(cmd2);
                var retval2 = pl2.Invoke();
                pl2.Stop();
            }
        }
        else
        {
            fails++;
        }
        pl.Stop();
    }
    rs.Close();
    rs = null;
}

答案 1 :(得分:0)

Runspace对象是Disposable,如果您编码,它是否相同:

using (Runspace rs = RunspaceFactory.CreateRunspace())
{
}