WMI ManagementObjectSearcher挂起查询

时间:2012-08-28 15:40:11

标签: c# .net wmi

我使用ManagementObjectSearcher进行WMI查询。

通常,这样可以正常工作,但在某些机器上,它会挂起/永不返回。我已经尝试在查询上设置超时,但似乎没有任何区别。

这是我的代码:

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

在我的日志中,我看到“查询已构建”,然后没有任何内容,程序也没有响应。

我尝试过使用和不使用手动超时设置。

2 个答案:

答案 0 :(得分:3)

最近我们在“C#命令行”测试了WMI查询,WMI按预期工作,但在WPF重写后,我们遇到了和你一样的问题。经过一些研究后,我发现如果你在STA(单线程公寓模式)中运行WMI,而WPF在STA模式下运行,那么执行任务我们正在使用ThreadPool(重写你的情况):

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

答案 1 :(得分:-3)

它应该在没有'使用'

的情况下工作
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") };
        }
    }
 }