Retrieve process network usage

前端 未结 3 1752
孤街浪徒
孤街浪徒 2020-12-02 13:35

How can I get a process send/receive bytes? the preferred way is doing it with C#.

I\'ve searched this a lot and I didn\'t find any simple solution for this. Some so

相关标签:
3条回答
  • 2020-12-02 14:02

    Resource monitor uses ETW - thankfully, Microsoft have created a nice nuget .net wrapper to make it easier to use.

    I wrote something like this recently to report back my process's network IO:

    using System;
    using System.Diagnostics;
    using System.Threading.Tasks;
    using Microsoft.Diagnostics.Tracing.Parsers;
    using Microsoft.Diagnostics.Tracing.Session;
    
    namespace ProcessMonitoring
    {
        public sealed class NetworkPerformanceReporter : IDisposable
        {
            private DateTime m_EtwStartTime;
            private TraceEventSession m_EtwSession;
    
            private readonly Counters m_Counters = new Counters();
    
            private class Counters
            {
                public long Received;
                public long Sent;
            }
    
            private NetworkPerformanceReporter() { }
    
            public static NetworkPerformanceReporter Create()
            {
                var networkPerformancePresenter = new NetworkPerformanceReporter();
                networkPerformancePresenter.Initialise();
                return networkPerformancePresenter;
            }
    
            private void Initialise()
            {
                // Note that the ETW class blocks processing messages, so should be run on a different thread if you want the application to remain responsive.
                Task.Run(() => StartEtwSession()); 
            }
    
            private void StartEtwSession()
            {
                try
                {
                    var processId = Process.GetCurrentProcess().Id;
                    ResetCounters();
    
                    using (m_EtwSession = new TraceEventSession("MyKernelAndClrEventsSession"))
                    {
                        m_EtwSession.EnableKernelProvider(KernelTraceEventParser.Keywords.NetworkTCPIP);
    
                        m_EtwSession.Source.Kernel.TcpIpRecv += data =>
                        {
                            if (data.ProcessID == processId)
                            {
                                lock (m_Counters)
                                {
                                    m_Counters.Received += data.size;
                                }
                            }
                        };
    
                        m_EtwSession.Source.Kernel.TcpIpSend += data =>
                        {
                            if (data.ProcessID == processId)
                            {
                                lock (m_Counters)
                                {
                                    m_Counters.Sent += data.size;
                                }
                            }
                        };
    
                        m_EtwSession.Source.Process();
                    }
                }
                catch
                {
                    ResetCounters(); // Stop reporting figures
                    // Probably should log the exception
                }
            }
    
            public NetworkPerformanceData GetNetworkPerformanceData()
            {
                var timeDifferenceInSeconds = (DateTime.Now - m_EtwStartTime).TotalSeconds;
    
                NetworkPerformanceData networkData;
    
                lock (m_Counters)
                {
                    networkData = new NetworkPerformanceData
                    {
                        BytesReceived = Convert.ToInt64(m_Counters.Received / timeDifferenceInSeconds),
                        BytesSent = Convert.ToInt64(m_Counters.Sent / timeDifferenceInSeconds)
                    };
    
                }
    
                // Reset the counters to get a fresh reading for next time this is called.
                ResetCounters();
    
                return networkData;
            }
    
            private void ResetCounters()
            {
                lock (m_Counters)
                {
                    m_Counters.Sent = 0;
                    m_Counters.Received = 0;
                }
                m_EtwStartTime = DateTime.Now;
            }
    
            public void Dispose()
            {
                m_EtwSession?.Dispose();
            }
        }
    
        public sealed class NetworkPerformanceData
        {
            public long BytesReceived { get; set; }
            public long BytesSent { get; set; }
        }
    }
    
    0 讨论(0)
  • 2020-12-02 14:13

    Have a look at the IP Helper API. There is an implementation in C# by Simon Mourier that sums transferred bytes per process: https://stackoverflow.com/a/25650933/385513

    It would be interesting to know how this compares with Event Tracing for Windows (ETW)...

    0 讨论(0)
  • 2020-12-02 14:28

    You can use PerformanceCounter. Sample code:

    //Define 
    string pn = "MyProcessName.exe";
    var readOpSec  = new PerformanceCounter("Process","IO Read Operations/sec", pn);
    var writeOpSec = new PerformanceCounter("Process","IO Write Operations/sec", pn);
    var dataOpSec  = new PerformanceCounter("Process","IO Data Operations/sec", pn);
    var readBytesSec = new PerformanceCounter("Process","IO Read Bytes/sec", pn);
    var writeByteSec = new PerformanceCounter("Process","IO Write Bytes/sec", pn);
    var dataBytesSec = new PerformanceCounter("Process","IO Data Bytes/sec", pn);
    
    var counters = new List<PerformanceCounter>
                    {
                    readOpSec,
                    writeOpSec,
                    dataOpSec,
                    readBytesSec,
                    writeByteSec,
                    dataBytesSec
                    };
    
    // get current value
    foreach (PerformanceCounter counter in counters)
    {
        float rawValue = counter.NextValue();
    
        // display the value
    }
    

    And this is to get performance counters for the Network card. Note it is not process specific

    string cn = "get connection string from WMI";
    
    var networkBytesSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", cn);
    var networkBytesReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", cn);
    var networkBytesTotal = new PerformanceCounter("Network Interface", "Bytes Total/sec", cn);
    
    Counters.Add(networkBytesSent);
    Counters.Add(networkBytesReceived);
    Counters.Add(networkBytesTotal);
    
    0 讨论(0)
提交回复
热议问题