private static void InitAdapter() { // Counter variables var counterLock = new object(); int received = 0; int sent = 0; // Fetch ID of all BaiduNetdisk processes var processList = Process.GetProcessesByName("BaiduNetdisk").Select(p => p.Id).ToHashSet(); GetProcessAndChildren(processList.First()); // Run in another thread, since this will be a blocking operation (see below) Task.Run(() => { // Start ETW session using (var session = new TraceEventSession("MyKernelAndClrEventsSession")) { // Query network events session.EnableKernelProvider(KernelTraceEventParser.Keywords.NetworkTCPIP); // Subscribe to trace events // These will be called by another thread, so locking is needed here session.Source.Kernel.TcpIpRecv += data => { if (list.Contains(data.ProcessID)) lock (counterLock) received += data.size; }; session.Source.Kernel.TcpIpSend += data => { if (list.Contains(data.ProcessID)) lock (counterLock) sent += data.size; }; // Process all events (this will block) session.Source.Process(); } }); // Program logic to handle counter values while (true) { // Wait some time and print current counter status Task.Delay(1000).Wait(); lock (counterLock) Console.WriteLine($"发送: {(sent / 1024.00).ToString("N")} kb/s 收到: {(received / 1024.00).ToString("N")} kb/s 总的:{((sent + received) / 1024.00).ToString("N")}"); } } private static List<int> list = new List<int>(); /** * 传入参数:父进程id * 功能:根据父进程id,获取相关的进程树 */ public static void GetProcessAndChildren(int pid) { ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid); ManagementObjectCollection moc = searcher.Get(); foreach (ManagementObject mo in moc) { GetProcessAndChildren(Convert.ToInt32(mo["ProcessID"])); } try { Process proc = Process.GetProcessById(pid); Console.WriteLine(pid); list.Add(pid); } catch (ArgumentException) { /* process already exited */ } }
版权归属:
管理员
许可协议:
本文使用《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》协议授权
评论区