0

Running WMI query against Win32_PageFileUsage class causes a memory leak. In my situation it is being done to 200 servers every 5 minutes. After about 3 hours the memory leak is nearly 10 GB. I think it is somehow relaited to that fact, that the pagefile does not exist. The value is "0". Here is my code:

...
ObjectQuery pageFileUsageQuery = 
        new ObjectQuery("SELECT AllocatedBaseSize, CurrentUsage FROM Win32_PageFileUsage");
m_PageFileUsageSearcher = new ManagementObjectSearcher(managementScope, pageFileUsageQuery);
...
var pageFileUsageCollection = m_PageFileUsageSearcher.Get();
double currentUsage = 0;
double maxSize = 0;

foreach (ManagementBaseObject managementBaseObject in pageFileUsageCollection)
{
        string result = managementBaseObject["CurrentUsage"].ToString();
        currentUsage += double.Parse(result);
}

The system is Windows Server 2008 SP2. Maybe somebody has any ideas?

Mihai Labo
  • 1,082
  • 2
  • 16
  • 40
  • I think this will answer your question: http://stackoverflow.com/questions/11896282/c-sharp-using-clause-fails-to-call-dispose/11896367#11896367 – Michael Graczyk Aug 10 '12 at 07:10

2 Answers2

1

ManagementObjectSearcher implements IDisposable(as does ManagementObjectCollection and ManagementBaseObject). You should dispose of these... perhaps with well placed using statements.

ObjectQuery pageFileUsageQuery = 
        new ObjectQuery("SELECT AllocatedBaseSize, CurrentUsage FROM Win32_PageFileUsage");
using(m_PageFileUsageSearcher = new ManagementObjectSearcher(managementScope, pageFileUsageQuery))
{
    ...
    using(var pageFileUsageCollection = m_PageFileUsageSearcher.Get())
    {
        double currentUsage = 0;
        double maxSize = 0;

        foreach (ManagementBaseObject managementBaseObject in pageFileUsageCollection)
        {
            try
            {
                string result = managementBaseObject["CurrentUsage"].ToString();
                currentUsage += double.Parse(result);
            }
            finally
            {
                managementBaseObject.Dispose();
            }
        }
    }
}
spender
  • 117,338
  • 33
  • 229
  • 351
  • :( Unfortunately it didn't help. – user1490500 Jun 29 '12 at 15:48
  • No success. I've disposed all objects and memory add on every cycle by 8kB. See the same problem by this post. https://stackoverflow.com/questions/8922601/wmi-memory-leak-solution – raiserle Sep 22 '17 at 16:57
0

As per comment above by michael-graczyk, there is a bug in the Dispose of …

Calling GC.WaitForPendingFinalizers() once is enough to fix it

though we do not consider it a solution really, just a workaround.

ac1965
  • 91
  • 1
  • 1