2012-03-16 32 views
1

我已經瀏覽了關於WMI的一些帖子,並且仍然有點麻煩。我想從WMI中檢索CPU使用率,我的查詢檢索ManagementObjectSearcher提供的所有內容,但它返回一個null值,並且不會返回任何信息。訪問WMI中的處理器數量

另外,對於數據類型,我拉我應該使用int16?

希望有人可以在這一點上發出一點點亮,並送我在我的路上。謝謝。

public void GetPhysicalMemory() 
{ 
    ManagementObjectSearcher mgtObj = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_ComputerSystem"); // Win32_OPeratingSystem"); 
    ManagementObjectCollection mgtColl = mgtObj.Get(); 

    // foreach (ManagementObject obj in mgtObj.Get()) 
    if (mgtColl.Count != 0) 
    { 
     foreach (ManagementBaseObject mgtBaseObj in mgtColl) 
     { 
      var[] data = mgtBaseObj["NumberOfProcessors"] as int16[]; 

      if (data != null) 
      { 
       Console.WriteLine(data); 
      } 
      else 
      { 
       Console.WriteLine("Collection = null"); 
       Console.Read(); 
       Console.Read(); 

      } 
     } 
    } 
+0

要獲取處理器的數量還是CPU使用率? – RRUZ 2012-03-16 14:35:09

+1

我實際上看起來更多地返回CPU使用率,我在黑暗中採取了刺傷措施,以便使用NumberOfProcessors撤回任何東西。 – jpavlov 2012-03-16 14:51:57

回答

0

你可以可以通過使用ManagementObject變量ManagementObjectSearcher.Get方法返回的集合直接循環,從這裏你可以訪問你可以訪問使用項目屬性或通過[]符號每個屬性。

檢查此示例應用程序。

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

namespace ConsoleFoo 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      try 
      { 
       ManagementObjectSearcher mgtObj = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_ComputerSystem"); 
       foreach (ManagementObject item in mgtObj.Get()) 
       { 
        Console.WriteLine("Number Of Processors {0}", item["NumberOfProcessors"]); 
       } 
      } 
      catch (ManagementException e) 
      { 
       Console.WriteLine("Exception {0} ", e.Message); 
      } 
      Console.ReadKey(); 
     } 
    } 
} 
+0

你知道哪個集合承載CPU使用率嗎? – jpavlov 2012-03-16 18:34:26

+0

您必須訪問性能計數器,請嘗試使用類似[Win32_PerfFormattedData_PerfProc_Process](http://msdn.microsoft.com/en-us/library/windows/desktop/aa394277%28v=vs.85%29.aspx) – RRUZ 2012-03-16 18:49:15