user833970
user833970

Reputation: 2799

WMI causing memory leak(when run in multiple threads)

My question is similar to Periodical WMI Query Causes Memory Leak? but with threads.

I am writing a simple application to monitor process and memory information from a number of servers. However there is a memory leak. I have whittled down the problem to the following simple Console application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Threading;


namespace ConsoleApplication1
{
    class Program
    {
        public static void dummyQuery(string ip, string query)
        {
            ConnectionOptions connOptions = new ConnectionOptions();
            ManagementScope mgtScope = new ManagementScope(@"\\" + ip + @"\ROOT\CIMV2", connOptions);


            mgtScope.Connect();

            ObjectQuery queryo = new ObjectQuery(query);

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(mgtScope, queryo))
            {

                using (ManagementObjectCollection moc = searcher.Get())
                {

                }
            }
        }

        static void Main(string[] args)
        {
            Console.ReadKey();
            int times = 10000;
            for (int i = 0; i < times; i++)
            {

                Thread t = new Thread(o => dummyQuery("xxxxxxxxx", @"SELECT WorkingSetSize FROM Win32_Process WHERE name='W3WP.exe'"));
                //t.IsBackground = true;

                t.Start();

                System.Threading.Thread.Sleep(50);
            }
            Console.ReadKey();
            //GC.Collect();
            Console.ReadKey();
        }
    }
}

Is there a way to run WMI queries from threads safely?

This is extracted from a much more complicated wpf application that checks the status of many servers much like the dummyQuery method. That application leaks memory at a disturbingly fast rate related to WMI calls. This sample looks like it is not leaking memory (Jim Mischel had a better way of checking this). I will install a profiler and take another look at the original app.

Upvotes: 0

Views: 1899

Answers (1)

Chris Langford
Chris Langford

Reputation: 56

I Know that this is might be considered a dead thread but it was top of the search list when I was looking for a solution to the ManagementObjectSearcher memory leak issue that I was having.

My application is a multithreaded application that was calling WMI on the main thread as part of the initialisation process. The application then spawned multiple thread non of which used WMI. However, the application kept leaking memory when run as a Windows service (it was OK if it was run as a standard executable).

Putting [MTAThread] attribute on the Main entrypoint resolved the problem.

Upvotes: 4

Related Questions