2014-02-24 114 views
1

我正在從PerformanceCounters讀取'%CPU'和'可用內存'的服務器上工作。 它適用於我的開發機器。但在實際的服務器上,從這兩個PerformanceCounter讀取真的很慢。至少在前兩次讀取操作中。
它可能需要長達4-6分鐘,在執行以下代碼:爲什麼對PerformanceCounter的調用很慢?

 Stopwatch watch = new Stopwatch(); 

     Log.Instance.Debug("Going to initialize Diagnostic's PerformanceCounters"); 

     watch.Start(); 

     m_CPUPerformanceCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true); 
     m_MemoryPerformanceCounter = new PerformanceCounter("Memory", "Available MBytes", true); 

     m_CPUPerformanceCounter.NextValue(); 
     m_MemoryPerformanceCounter.NextValue(); 

     //Ensure an updated value... 
     System.Threading.Thread.Sleep(1000); 

     m_CPUPerformanceCounter.NextValue(); 
     m_MemoryPerformanceCounter.NextValue(); 

     watch.Stop(); 

     Log.Instance.Debug("Finished initializing Diagnosticss PerformanceCounters. Time elapsed: {0}", watch.Elapsed); 

當我運行我的開發機器上的代碼,它將在完成不超過2秒(有時甚至更低)。但是在我們的產品的客戶應該使用的實際服務器上,這將需要很長時間。請看下圖:

Finished initializing Diagnosticss PerformanceCounters. Time elapsed: 00:03:59.6706860 

,這些讀操作(以及後來的「讀」操作)是很重要的將執行非常快。甚至在一開始。

我的開發機器是Windows 7,64位,8GB RAM。
客戶端服務器是Windows Server 2008 R2 Enterprise,64位,4 GB RAM。

我谷歌搜索(和Binged)它,但無法找到任何答案。 這是怎麼回事?我該如何解決它?

+1

我不知道問題是什麼,但是:「//確保更新的值...... System.Threading.Thread.Sleep(1000);'肯定不能確保值得到更新。 – Tarec

+0

你爲什麼要將計數器指定爲只讀模式的訪問?作爲測試嘗試新的PerformanceCounter(「處理器」,「處理器時間百分比」,「_Total」); - 你確定你沒有隱藏異常嗎?例如UnauthorizedAccessException –

+0

@Tarec你是對的。但如果需要的話,操作系統有足夠的時間來更新這些PerformanceCounters。 – m1o2

回答

0

該問題很可能是由受監視系統上安裝的附加軟件提供的計數器。

在這種情況下,您應該對系統註冊表中註冊的所有性能計數器執行性能計數器初始化掃描,這可以使用ProcMon完成。