首页 > 解决方案 > C# 控制台应用程序(WMI 查询)突然填满内存

问题描述

我有一个 C# 应用程序,它创建 CimSession 或 ManagementScope 连接,并每秒在数十台远程 PC 上并行查询“PercentProcessorTime”。通常,该应用程序可以正常运行几个小时,然后突然开始填满内存。平均 100MB 的 RAM 使用量在一小时内跃升至 4-5GB。我无法找出这里发生了什么。以下是每秒运行的两种方法:

public static bool DumpProcessesCpu(string hostname)
    {
        bool overTreshold = false;
        try
        {
            CimSessionOptions sessionOptions = new CimSessionOptions() { Timeout = TimeSpan.FromSeconds(5) };
            using (CimSession mySession = CimSession.Create(hostname, sessionOptions))
            {
                string Namespace = @"root\cimv2";
                
                IEnumerable<CimInstance> queryInstance = mySession.QueryInstances(Namespace, "WQL", queryString);

                foreach (CimInstance cimInstance in queryInstance)
                {
                    int currentValue = Convert.ToInt32(cimInstance.CimInstanceProperties["PercentProcessorTime"].Value);
                    if (showLiveData == "true") Log.Debug("{0} - {1}", hostname, currentValue.ToString());

                    if (currentValue >= treshold)
                    {
                        overTreshold = true;
                    }
                }
            }
        }
        catch (SystemException e)
        {
            Log.Error("An error occurred while querying for WMI data for " + hostname + ": " + e.Message);
        }
        return overTreshold;
    }

public static bool DumpProcessesCpuLegacy(string hostname)
    {
        bool overTreshold = false;
        try
        {  
            ConnectionOptions options = new ConnectionOptions() { Timeout = TimeSpan.FromSeconds(5) };
            ObjectQuery query = new ObjectQuery(queryString);
            ManagementScope scope = new ManagementScope(@"\\" + hostname + @"\root\cimv2", options);
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
            {    
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    int currentValue = Convert.ToInt32("" + queryObj["PercentProcessorTime"]);
                    if (showLiveData == "true") Log.Debug("{0} - {1}", hostname, currentValue.ToString());

                    if (currentValue >= treshold)
                    {
                        overTreshold = true;
                    }
                }
            }
        }
        catch (ManagementException e)
        {
            Log.Error("An error occurred while querying for WMI data for " + hostname + ": " + e.Message);
        }

        return overTreshold;
    }

我正在使用 Parallel.Foreach 每秒在每台远程 PC 上运行这些方法之一。我到处都在使用广泛的日志记录和 try-catch,并且没有错误消息。

这里可能是什么问题?我应该在哪里继续调查?

谢谢

标签: c#memory-management

解决方案


推荐阅读