我使用计时器来获取每秒的带宽,并将这些信息放在标签上,输出值很大,比如419000KB/S,下一个选项可能是0KB/S。这是一个与线程有关的问题吗?我想是bytes不能正确地更新,但我不知道要修复它。
public partial class MainWindow : Window
{
static long bytes = 0;
static NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
static Label uploadLabel;
public MainWindow()
{
InitializeComponent();
uploadLabel = uploadBandwidth;
IPv4InterfaceStatistics statistics = adapters[0].GetIPv4Statistics();
bytes = statistics.BytesSent;
Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler(TimeUp);
myTimer.Interval = 1000;
myTimer.Start();
}
public void TimeUp(object source, ElapsedEventArgs e)
{
IPv4InterfaceStatistics statistics = adapters[0].GetIPv4Statistics();
bytes = statistics.BytesSent - bytes;
Dispatcher.Invoke(DispatcherPriority.Normal, new Action<Label>(SetValue), uploadLabel);
}
private void SetValue(Label upload)
{
upload.Content = ((int)bytes / 1024).ToString() + "KB/s";
}
}更新:
问题是我将值bytes更改为statistics.BytesSent - bytes,这是错误的。下面是我修改的函数:
public void TimeUp(object source, ElapsedEventArgs e)
{
IPv4InterfaceStatistics statistics = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics();
long bytesPerSec = statistics.BytesReceived - bytes;
bytes = statistics.BytesReceived;
String speed = (bytesPerSec / 1024).ToString() + "KB/S";
Dispatcher.Invoke(DispatcherPriority.Normal, new Action<Label, String>(SetValue), uploadLabel, speed);
}
private void SetValue(Label upload, String speed)
{
upload.Content = speed;
}发布于 2016-01-02 15:14:42
你的逻辑有问题。
开始时,您将迄今发送的数据存储在bytes中
uploadLabel = uploadBandwidth;
IPv4InterfaceStatistics statistics = adapters[0].GetIPv4Statistics();
bytes = statistics.BytesSent; // initialize bytes to amount already sent然后,在每个事件上,重置包含BytesSent - bytes的值。
IPv4InterfaceStatistics statistics = adapters[0].GetIPv4Statistics();
bytes = statistics.BytesSent - bytes;因此,假设您从每秒钟发送15k并发送1kB开始,变量如下:
|| seconds elapsed | BytesSent | bytes ||
||=================|===========|=======||
|| 0 | 15000 | 15000 ||
|| 1 | 16000 | 1000 ||
|| 2 | 17000 | 16000 ||
|| 3 | 18000 | 2000 ||因此,正如您所看到的,bytes值是交替的,在任何情况下都不显示任何合法值,只有第一种情况除外。
为了解决您的问题,您需要引入第二个状态变量,或者以与@Sign类似的正确方式将字节值传递给SetValue方法:
public void TimeUp(object source, ElapsedEventArgs e)
{
IPv4InterfaceStatistics statistics = adapters[0].GetIPv4Statistics();
var sent = statistics.BytesSent - bytes;
Dispatcher.Invoke(DispatcherPriority.Normal, new Action<Label>(SetValue), uploadLabel, sent);
bytes = statistics.BytesSent;
}https://stackoverflow.com/questions/34566699
复制相似问题