Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WMI ManagementObjectSearcher hanging on query

Tags:

c#

.net

wmi

I have a WMI Query, using ManagementObjectSearcher.

Usually, this works fine, but on some machines, it is hanging / never returning. I've tried setting a timeout on the query, but it appears to make no difference.

This is my code:

using (var query = new ManagementObjectSearcher("SELECT IDProcess, PercentProcessorTime, WorkingSet FROM Win32_PerfFormattedData_PerfProc_Process"))
{
   try
   {
        query.Options.Timeout = new TimeSpan(0, 0, 10);
        query.Options.ReturnImmediately = false;
        Log.Info("Query built");
        foreach (ManagementObject obj in query.Get())
        {
            using (obj)
            {
                var key = (uint)obj.GetPropertyValue("IDProcess");
                Log.Info(key);
                processStats[key] = new ulong[] { (ulong)obj.GetPropertyValue("PercentProcessorTime"), (ulong)obj.GetPropertyValue("WorkingSet") };
            }
        }
    }
}

In my log, I see "Query built", and then nothing and the program becomes unresponsive.

I've tried with and without the manual timeout setting.

like image 295
tomwardill Avatar asked Aug 28 '12 15:08

tomwardill


1 Answers

Recently we've tested WMI queries at "C# command line" and WMI worked as expected, but after rewriting in WPF we faced the same problem as you. After some research i've found that WMI hanging if you operating in STA(Single Threading Apartment mode ) but WPF operating in STA mode, so to perform the task we're using ThreadPool(rewriting to your case):

        ThreadPool.QueueUserWorkItem((_) =>
            {
                using (var query = new ManagementObjectSearcher("SELECT IDProcess, PercentProcessorTime, WorkingSet FROM Win32_PerfFormattedData_PerfProc_Process"))
                {
                    try
                    {
                        query.Options.Timeout = new TimeSpan(0, 0, 10);
                        query.Options.ReturnImmediately = false;
                        Log.Info("Query built");
                        foreach (ManagementObject obj in query.Get())
                        {
                            using (obj)
                            {
                                var key = (uint)obj.GetPropertyValue("IDProcess");
                                Log.Info(key);
                                processStats[key] = new ulong[] { (ulong)obj.GetPropertyValue("PercentProcessorTime"), (ulong)obj.GetPropertyValue("WorkingSet") };
                            }
                        }
                    }
                    catch (SystemException)
                    {
                    }
                }
            });
like image 192
Konstantin Sokharev Avatar answered Nov 15 '22 21:11

Konstantin Sokharev