首頁  >  文章  >  後端開發  >  詳細介紹C#伺服器效能監控之效能計數器的程式碼範例

詳細介紹C#伺服器效能監控之效能計數器的程式碼範例

黄舟
黄舟原創
2017-03-14 14:01:072960瀏覽

上一篇文章《伺服器效能監控之WMI》介紹了透過遠端com取得伺服器效能(當然也可用於本地),那麼這篇主要說說windows系統自帶的效能監視功能-----> ;performancecouonter.

#開啟管理工具-->效能,我們可以立即看到伺服器的CPU,進程運行時間,磁碟容量等效能參數走勢圖。然而不僅僅是這幾項,我們可以透過添加技術器來查看其他的性能指標:

如果你說,這麼看太麻煩了,OK,我們通過C#將這些值取出來,用於實現自身的效能監視:

1.新增引用

using System.Diagnostics;

2.建立並實例化PerformanceCounter

public static System.Diagnostics.PerformanceCounter pc= new System.Diagnostics.PerformanceCounter();
public static System.Diagnostics.PerformanceCounter pcm= new System.Diagnostics.PerformanceCounter();
public static System.Diagnostics.PerformanceCounter pcb= new System.Diagnostics.PerformanceCounter();
public static System.Diagnostics.PerformanceCounter pcc= new System.Diagnostics.PerformanceCounter();
//我们用四个对象做不同的操作,注意:是static的,不然每次取出的数据都是初始值,如cpu利用率就是0

3.建構子

static CapabilityScout()
...{
pc.CategoryName = "Processor";
pc.CounterName = "% Processor Time";
pc.InstanceName = "_Total";
pc.MachineName = ".";
pcm.CategoryName = "Memory";
pcm.CounterName = "% Committed Bytes In Use";
pcm.MachineName = ".";
pcb.CategoryName = "Windows Media Unicast Service";
pcb.CounterName = "Allocated Bandwidth";
pcb.MachineName = ".";
pcc.CategoryName = "Windows Media Unicast Service";
pcc.CounterName = "Connected Clients";
pcc.MachineName = ".";
}

4.取得計數器值

    获取CPU利用率#region 获取CPU利用率
        public static string getCpuUsage()
        ...{
            string used = pc.NextValue().ToString();
            return used;
        }
        #endregion
        获取内存使用率#region 获取内存使用率
        public static string getMemory()
        ...{
            float used = pcm.NextValue();
            return used.ToString();
        }
        #endregion
        获取WMS连接数#region 获取WMS连接数
        public static string getConnectedCount()
        ...{
            string count = pcc.NextValue().ToString();
            return count;
        }
        #endregion
        获取网络流量#region 获取网络流量
        public static string getServerBandWidth()
        ...{
            string bandwidth = pcb.NextValue().ToString();
            return bandwidth;
        }
        #endregion

當然,這裡只是其中及少的部分,不過透過使用同樣的方式,我們可以獲得更多的性能以及進程運行的情況,但是要說明的一點是,所獲取的數據必定是windows服務所提供的,當然我們也可以自己寫一些windows服務,添加到系統performancecounter中來,對.net來說也是非常方便的。

怎麼樣,跟WMI比起來,是不是又方便了一些呢,呵呵~~

 

以上是詳細介紹C#伺服器效能監控之效能計數器的程式碼範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn