簡體   English   中英

使用PerformanceCounter獲取進程的CPU使用率

[英]Get CPU usage of process with PerformanceCounter

我正在嘗試獲取特定進程的CPU使用率,但它僅返回0。我仍然不知道問題出在哪里。

Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
    if (GetProcessOwner(theprocess.Id) != "NO_OWNER")
    {
        if (theprocess.ProcessName != "svchost")
        {
            var ram = BytesToString(theprocess.PeakWorkingSet64);
            ram = ram.Replace("MB", "");

            string state = "";

            if (theprocess.MainWindowTitle == "") 
            {
                state = "background";
            }
            else 
            {
                state = "foreground";
            }

            sw.WriteLine("ID=" + theprocess.Id + "&NAME=" + theprocess.ProcessName + "&RAM=" + ram + "&STARTED=" + theprocess.StartTime + "&STATE=" + state);
            PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", theprocess.ProcessName);
            Console.WriteLine("CPU="+counter.NextValue());
        }
    }
}

沒關系,因為下次調用NextValue時始終返回0

為了解決此錯誤,您可以在創建PerformanceCounter對象(耐用性黑客)后兩次調用NextValue函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM