问题
I'm creating a C# WinForm Application which will display Network Activity (Bytes Received / Bytes Sent) for a given Process (For Example: Process name 's chrome.exe
) and Speed in Megabyte/s generated by the Process.
My application uses Performance Counter Class to get the Process activities like IO Read Bytes/sec
for received bytes and IO Writes Bytes/sec
for sent bytes. But, it's giving me 0 Bytes as a result, which's very weird because chrome.exe
is running and its definitely using some bytes data.
Researches that I've tried to find the solution are:
- https://stackoverflow.com/a/17026417/5377037
- C# Resource Monitor get network activity values
- https://www.c-sharpcorner.com/forums/i-want-to-develop-resource-monitor-desktop-application
Here is some code that I'm using :
PerformanceCounter PC = new PerformanceCounter();
PC.CategoryName = "Process";
PC.CounterName = "IO Read Bytes/sec";
PC.InstanceName = "chrome";
PC.ReadOnly = true;
Console.WriteLine("Bytes Receieved: " + Math.Round(PC.NextValue()));
PC.CounterName = "IO Write Bytes/sec";
Console.WriteLine("Bytes Sent: " + Math.Round(PC.NextValue()));
Results:
Bytes Received: 0
Bytes Sent: 0
回答1:
According to the documentation:
If the calculated value of a counter depends on two counter reads, the first read operation returns 0.0. Resetting the performance counter properties to specify a different counter is equivalent to creating a new performance counter, and the first read operation using the new properties returns 0.0. The recommended delay time between calls to the NextValue method is one second, to allow the counter to perform the next incremental read.
来源:https://stackoverflow.com/questions/57972891/getting-0-bytes-in-results-for-the-given-process-using-performance-counter-in-c