WMI ManagementObjectSearcher hanging on query
.net, c#, wmi
Solution
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)
{
}
}
});
Problem
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.