gpt4 book ai didi

c# - 获取网络带宽信息

转载 作者:行者123 更新时间:2023-11-30 18:22:01 24 4
gpt4 key购买 nike

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

最佳答案

你的逻辑有问题。

一开始,您以字节存储到目前为止发送的数据:

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

关于c# - 获取网络带宽信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34566699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com