获取网络带宽信息

本文关键字:信息 网络带宽 获取 | 更新日期: 2023-09-27 18:28:39

我使用计时器来获得每秒的带宽,并将该信息放在标签上。输出是一个大值,如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;
}

获取网络带宽信息

您的逻辑有问题。

一开始,您将迄今为止发送的数据存储在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;
}