WMI ManagementObjectSearcher freezing upon request

I have a WMI request using ManagementObjectSearcher.

This usually works fine, but on some machines it hangs / does not return. I tried setting a timeout in the request, but it doesn't seem to matter.

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 stops responding.

I tried with manual timeout settings and without it.

+7
source share
2 answers

We recently tested WMI queries on the "C #" command line, and WMI worked as expected, but after overwriting it in WPF, we ran into the same problem as you. After some research, I found that WMI hangs if you work in STA (Single Threading Apartment) mode, but WPF works in STA mode, so we use ThreadPool (to rewrite for your case) to complete the task:

  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) { } } }); 
+3
source

it should work without "use"

 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") }; } } } 
-3
source

All Articles