上一篇文章《伺服器性能監控之WMI》介紹了通過遠端com擷取伺服器性能(當然也可用于本地),那麼這篇主要說說windows系統自帶的性能監視功能----->performancecouonter.
打開管理工具-->性能,我們可以立即看到伺服器的CPU,程序運作時間,磁盤容量等性能參數走勢圖。然而不僅僅是這幾項,我們可以通過添加技術器來檢視其他的性能名額:
如果你說,這麼看太麻煩了,OK,我們通過C#将這些值取出來,用于實作自身的性能監視:
1.添加引用:
usingSystem.Diagnostics;
2.建立并執行個體化PerformanceCounter
publicstaticSystem.Diagnostics.PerformanceCounterpc=newSystem.Diagnostics.PerformanceCounter();
publicstaticSystem.Diagnostics.PerformanceCounterpcm=newSystem.Diagnostics.PerformanceCounter();
publicstaticSystem.Diagnostics.PerformanceCounterpcb=newSystem.Diagnostics.PerformanceCounter();
publicstaticSystem.Diagnostics.PerformanceCounterpcc=newSystem.Diagnostics.PerformanceCounter();
//我們用四個對象做不同的操作,注意:是static的,不然每次取出的資料都是初始值,如cpu使用率就是0
3.構造函數
staticCapabilityScout()
...{
pc.CategoryName="Processor";
pc.CounterName="%ProcessorTime";
pc.InstanceName="_Total";
pc.MachineName=".";
pcm.CategoryName="Memory";
pcm.CounterName="%CommittedBytesInUse";
pcm.MachineName=".";
pcb.CategoryName="WindowsMediaUnicastService";
pcb.CounterName="AllocatedBandwidth";
pcb.MachineName=".";
pcc.CategoryName="WindowsMediaUnicastService";
pcc.CounterName="ConnectedClients";
pcc.MachineName=".";
}
4.擷取計數器值
擷取CPU使用率#region擷取CPU使用率
publicstaticstringgetCpuUsage()
stringused=pc.NextValue().ToString();
returnused;
#endregion
擷取記憶體使用率#region擷取記憶體使用率
publicstaticstringgetMemory()
floatused=pcm.NextValue();
returnused.ToString();
擷取WMS連接配接數#region擷取WMS連接配接數
publicstaticstringgetConnectedCount()
stringcount=pcc.NextValue().ToString();
returncount;
擷取網絡流量#region擷取網絡流量
publicstaticstringgetServerBandWidth()
stringbandwidth=pcb.NextValue().ToString();
returnbandwidth;
當然,這裡隻是其中及少的部分,不過通過使用同樣的方式,我們可以擷取更多的性能以及程序運作的情況,但是要說明的一點是,所擷取的資料必定是windows服務所提供的,當然我們也可以自己寫一些windows服務,添加到系統performancecounter中來,對.net來說也是非常友善的。
怎麼樣,和WMI比起來,是不是又友善了一些呢,呵呵~~