由於之前的一個想法,所以開始測試如何使用 C# 抓取各個系統執行中的程序與 CPU 使用量。由於先前沒有動過相關的語法,所以特別上網去找了相關的資料。(Keyword : Csharp process CPU usage)。
接著就找到在 System.Diagnostics(英) namespace 下有各種可以監控系統狀況的類別與方法。在其中就有一個類別 PerformanceCounter (效能監視器計數器) 就是我們這次要用到的東西。而這項工具也就是在控制台中的「資源監視器」或「效能監視器」一類的東西(如圖)。
(圖:效能監視器)
(圖:資源監視器)
接著就來看如何來應用 PerformanceCounter 來取得我們要的資源。
在 Library 中表示 PerformanceCounter 的 Constructors 有六個,主要差異在於是否預設效能計數器類型 ( Performance Counter Category ) 的物件名稱 ( _categoryName ) 、該分類下計數器的名稱 ( _counterName ) 、執行個體的名稱 ( _instanceName ) 或者是否為唯讀( _Read-only ),以及所在電腦名稱 ( _machineName )。
1. | PerformanceCounter() |
2. | PerformanceCounter( String _categoryName , String _counterName) |
3. | PerformanceCounter( String _categoryName , String _counterName , Boolean _Read-only ) |
4. | PerformanceCounter( String _categoryName , String _counterName , String _instanceName ) |
5. | PerformanceCounter( String _categoryName , String _counterName , String _instanceName , Boolean _Read-only ) |
6. | PerformanceCounter( String _categoryName , String _counterName , String _instanceName , String _machineName ) |
為了取得這些類型的名稱,我們可以利用 PerformanceCounter 中的一些方法來實現我們的目標,例如要取得 Category Name,利用 PerformaceCounterCategory 中的 GetCategories 方法即可取得電腦中用的類別名稱。
using System.Diagnostics; // Performance Counter using System.ComponentModel;// W32 Exception /*************************************************/ private static void GetCategoryName() { PerformanceCounterCategory[] performanceCounterCategory; try{ performanceCounterCategory = PerformanceCounterCategory.GetCategories(); foreach (PerformanceCounterCategory pCounterCategory in performanceCounterCategory) { Console.WriteLine("["+pCounterCategory.CategoryName+"]"); } } catch(Win32Exception wException) { Console.writeLine(wException); } } /*************************************************/
而在我所需要的程式中,必須取得各個程序的 CPU 使用率( CPU usage ),若要取得該資源,必須使用 "Process" 這個分類名稱。接著再去取得該分類下的執行個體名稱,利用 PerformanceCounterCategory 中的 GetInstanceNames 方法來達成要求。
private static void GetInstanceNameOfCategory(String _categoryName) { PerformanceCounterCategory category = new PerformanceCounterCategory(_categoryName); // Get the instance name of category in perfomance counter string[] instanceNames; // Store the instance's name ArrayList counters = new ArrayList(); // Store the counters' name try { instanceNames = category.GetInstanceNames(); if (instanceNames.Length == 0) { counters.AddRange(category.GetCounters()); } else // if the category exist the instances , store its' name { for (int i = 0; i < instanceNames.Length; i++) { counters.AddRange(category.GetCounters(instanceNames[i])); } } foreach (string name in instanceNames) // print out all of the instance name { Console.WriteLine("\t[" + name + "]"); } } catch (InvalidOperationException invalidOpreationException) { Console.WriteLine(invalidOpreationException); } catch (Win32Exception wException) { Console.WriteLine(wException); } }
接著即可看到在目前本機電腦中執行的所有程序。