NetworkMonitor底层实现
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;a
using System.Timers;
namespace NetMonitor
{
class NetworkMonitorSM
{
public double timerInterval = 1000;
public string networkName = "";
public Action<MonitorInfo> callback = null;
Timer timer = null;
List<PerformanceCounter> downloadCounters = null;
List<PerformanceCounter> uploadCounters = null;
public NetworkMonitorSM()
{
downloadCounters = new List<PerformanceCounter>();
uploadCounters = new List<PerformanceCounter>();
}
public void StartMonitor()
{
InitTimer();
InitNetCategory();
timer.Start();
}
public void InitTimer()
{
timer = new Timer();
timer.Interval = timerInterval;
timer.Elapsed += timer_Elapsed;
}
public void InitNetCategory()
{
PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
foreach (string name in category.GetInstanceNames())
{
if (name == "MS TCP Loopback interface")
continue;
if (!string.IsNullOrEmpty(networkName))
{
if (networkName.Equals(name))
{
downloadCounters.Add(new PerformanceCounter("Network Interface", "Bytes Received/sec", name));
uploadCounters.Add(new PerformanceCounter("Network Interface", "Bytes Sent/sec", name));
}
}
else
{
downloadCounters.Add(new PerformanceCounter("Network Interface", "Bytes Received/sec", name));
uploadCounters.Add(new PerformanceCounter("Network Interface", "Bytes Sent/sec", name));
}
}
if (downloadCounters.Count <= 0)
Console.WriteLine("Do not Has the Network named with [" + networkName + "]");
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
float totalDownlaod = 0;
float totalUplaod = 0;
foreach (PerformanceCounter pc in downloadCounters)
{
totalDownlaod += pc.NextValue();
}
foreach (PerformanceCounter pc in uploadCounters)
{
totalUplaod += pc.NextValue();
}
MonitorInfo mi = new MonitorInfo();
mi.downloadBytes = totalDownlaod;
mi.uploadBytes = totalUplaod;
if (callback != null)
callback(mi);
}
}
public class MonitorInfo
{
public double downloadBytes;
public double uploadBytes;
public override string ToString()
{
int d = (int)(downloadBytes / 1024f);
int u = (int)(uploadBytes / 1024f);
string ds = "k/s";
string us = "k/s";
return "D : " + d.ToString() + ds + " U : " + u.ToString() + us;
}
}
}
调用方法
private void MonitorStart()
{
NetworkMonitorSM sm = new NetworkMonitorSM();
sm.callback += MonitorCallBack;
sm.StartMonitor();
}
private void MonitorCallBack(MonitorInfo info)
{
Console.WriteLine(info.ToString());
}
网友评论