获取网络带宽信息

时间:2016-01-02 14:00:30

标签: c#

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

1 个答案:

答案 0 :(得分:0)

你的逻辑存在问题。

开始时,您将目前发送的数据存储在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值是交替的,并且在任何情况下都没有显示任何合法值,除了第一个。

为了解决您的问题,您需要引入第二个状态变量或以正确的方式将字节值传递给SetValue方法,类似于@Sign回答:

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;
}