Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#System.Management.Automation.Powershell类调用Invoke()时内存泄漏_C#_Powershell_System.management - Fatal编程技术网

C#System.Management.Automation.Powershell类调用Invoke()时内存泄漏

C#System.Management.Automation.Powershell类调用Invoke()时内存泄漏,c#,powershell,system.management,C#,Powershell,System.management,我有一个C#测试应用程序的代码,该应用程序使用PowerShell查询系统信息,其中有几个简单的函数,如下所示: public void GetSystemInfo() { using (PowerShell ps = PowerShell.Create()) { ps.AddCommand("Get-Disk"); // Get-Disk is an example; this varies foreach (PSObject resu

我有一个C#测试应用程序的代码,该应用程序使用PowerShell查询系统信息,其中有几个简单的函数,如下所示:

public void GetSystemInfo()
{
    using (PowerShell ps = PowerShell.Create())
    {
        ps.AddCommand("Get-Disk");      // Get-Disk is an example; this varies
        foreach (PSObject result in ps.Invoke())
        {
            // ...
            // Do work here. Process results, etc...
            // ...
        }
    }
}
这很简单,主要取自MSDN示例,如下所示:

问题是,每次调用此函数时,我都能看到应用程序的内存占用增加。在调用ps.Invoke()时,封装外形会立即增大,并且不会缩小。 我如何处理数据并不重要;我甚至可以完全注释foreach循环的主体,而且内存永远不会被垃圾收集

就我看PowerShell类所知,似乎没有办法强制它进行自我清理,而且Dispose()显然不起作用,因为在using块退出后,内存中的资源仍在泄漏

这是C#PowerShell类实现中的已知bug还是PowerShell本身? 是否有人知道解决方案,或可能的替代方案


编辑 我现在也尝试了以下方法,得到了相同的结果:

public void GetSystemInfo()
{
    Runspace rs = RunspaceFactory.CreateRunspace();
    rs.Open();

    PowerShell ps = PowerShell.Create();
    ps.Runspace = rs;
    ps.AddCommand("Get-Disk");      // Get-Disk is an example; this varies
    foreach (PSObject result in ps.Invoke())
    {
        // ...
        // Do work here. Process results, etc...
        // ...
    }

    rs.Close();
}
同样,超级简单。从样品中提取


我想知道这是否是Powershell模块中的已知错误。也许我会开始寻找Powershell接口(WMI等)的替代方案,因为我需要在不确定的长时间内定期调用这些PS查询。

C#库中的Powershell API确实存在问题。即使强制垃圾收集似乎也无法释放内存


用WMI调用而不是Powershell替换所有调用可以解决此问题。

我对此不确定,因此我不会将其添加为答案,但内存可能在运行空间中,而不是Powershell对象中。如果您使用RunspaceFactory管理自己的运行空间或运行空间池,然后在完成后尝试清理这些对象会怎么样?谢谢您的建议。我会试试,然后向邮报汇报。可能会在Microsoft User Voice/MSDN User Voice或其他内容上引发此问题。同时,您可以按照
ISystemManagment
的思路编写一个接口(或者根据您正在编写的代码编写一个更好的名称),该接口提供了所需的方法。然后有两个类,它们都实现了
ISystemManagment
,但一个类通过WMI实现,另一个类通过Powershell实现。如果Powershell问题得到解决,则可以更轻松地交换功能。例如,两个类中都有
GetSystemInfo
,但一个类使用WMI,另一个类使用Powershell。反正只是个建议。