Заметил, что форма притормаживает раз в секунду... то есть метод GetIPv4Statistics работает не так быстро как хотелось бы...
Вот пример с потоками (используется потоковый таймер):
Код | using System; using System.Windows.Forms; using System.Net.NetworkInformation;
namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent();
kbytesFromStart = bytesPerSecond = -1;
NetworkInterface[] niArray = NetworkInterface.GetAllNetworkInterfaces(); if (niArray.Length == 0) throw new InvalidOperationException();
// !!! У меня нулевой индекс интерфейса интернета // !!! У тебя может быть и другой // !!! Лучше предоставить пользователю выбор из списка networkInterface = niArray[0]; startRecivedBytes = lastRecivedBytes = this.GetRecivedBytes();
timer = new System.Threading.Timer(timer_Callback, null, 0, 1000); }
System.Threading.Timer timer; NetworkInterface networkInterface; int startRecivedBytes, lastRecivedBytes; Action<Label, string> updateLabel = new Action<Label, string>((label, text) => label.Text = text);
private int GetRecivedBytes() { IPv4InterfaceStatistics ipv4Stat = networkInterface.GetIPv4Statistics(); return (int)(ipv4Stat.BytesReceived); }
int kbytesFromStart; private void SetKBytesFromStart(int value) { if (kbytesFromStart == value) return; kbytesFromStart = value;
string text = string.Format("С момента запуска программы, получено {0} КБ.", kbytesFromStart); if (label1.InvokeRequired) label1.Invoke(updateLabel, label1, text); else updateLabel(label1, text); }
int bytesPerSecond; private void SetBytesPerSecond(int value) { if (bytesPerSecond == value) return; bytesPerSecond = value;
string text = string.Format("Скорость получения {0} байт/сек.", bytesPerSecond); if (label2.InvokeRequired) label2.Invoke(updateLabel, label2, text); else updateLabel(label2, text); }
private void timer_Callback(object state) { int recivedBytes = this.GetRecivedBytes();
this.SetKBytesFromStart((recivedBytes - startRecivedBytes) / 1024); this.SetBytesPerSecond(recivedBytes - lastRecivedBytes);
lastRecivedBytes = recivedBytes; } } }
|
|