1

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:

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
  • That counter is sampled, not cumulative. At the very moment you read it, no bytes were being transferred. Check `RawValue` and/or read the counter periodically (it'll take a second for the value to start becoming useful). – Jeroen Mostert Sep 17 '19 at 11:15
  • I used `RawValue` and it's giving this 576729973 which impossible value. –  Sep 17 '19 at 11:20
  • No -- that means that Chrome has read 576729973 bytes since it started. You'll see it go up as you read it again. The whole "per second" thing only comes into play when you read `NextValue()` periodically. – Jeroen Mostert Sep 17 '19 at 11:25
  • A foo/sec counter value requires waiting for a second to obtain the next value. It then tells you what happened during that last second. Nothing happened yet when you first read it, so you get 0. Use a timer to sample it. – Hans Passant Sep 17 '19 at 11:33

1 Answers1

2

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.

Markus Safar
  • 6,324
  • 5
  • 28
  • 44
  • I got your answer. Can you tell me how I can get Speed in MB generated by this process? –  Sep 17 '19 at 11:41
  • @5377037: You mean the currently used speed in MBit/s or the total amount sent/received by this process? – Markus Safar Sep 17 '19 at 12:08