簡體   English   中英

如何在C#中顯示每秒接收的字節數

[英]How to display bytes received per second in C#

我正在嘗試每秒顯示接收的字節,並每秒將它們顯示在控制台中一次。 一旦達到.nextvalue,我將收到一個無效的操作異常。

PerformanceCounter NetworkDownSpeed = new PerformanceCounter("Network Interface", "Bytes Received/sec");
float CurrentNetworkDownSpeed = (int)NetworkDownSpeed.NextValue();

while (true)
{
    Console.WriteLine("Current Network Download Speed: {0}MB", CurrentNetworkDownSpeed);
    Thread.Sleep(1000);
}

對不起,已經有人回答了,但這對您有幫助嗎?

private static void ShowNetworkTraffic()
{
    PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
    string instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC !
    PerformanceCounter performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
    PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);

    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine("bytes sent: {0}k\tbytes received: {1}k", performanceCounterSent.NextValue() / 1024, performanceCounterReceived.NextValue() / 1024);
        Thread.Sleep(500);
    }
}

這里

NetworkDownSpeed.NextValue()可以引發InvalidOperationException。

NetworkDownSpeed.NextValue中,有一條注釋詳細說明了原因。

// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.

可以在此堆棧溢出文章中找到解決此問題的替代解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM