带宽监控系统

时间:2013-04-26 17:06:46

标签: vb.net loops bandwidth

我正在尝试监控我的互联网连接的流量,即在给定时间的平均速度,以获得平均速度。我试过这个代码,但它没有用。我哪里错了?

Function bwmonitor()
    Dim pc As New PerformanceCounterCategory("Network Interface")
    Dim instance As String = pc.GetInstanceNames(0)
    Dim bs As New PerformanceCounter("Network Interface", "Bytes Sent/sec", instance)
    Dim br As New PerformanceCounter("Network Interface", "Bytes Received/Sec", instance)
    Dim k As Integer = 0

    Do
        k = k + 1
        Dim kbsent As Integer = bs.NextValue() / 1024
        Dim kbRecieved As Integer = br.NextValue / 1024
        TextBox10.Text = kbsent
        TextBox11.Text = kbRecieved
        Threading.Thread.Sleep(1000)
    Loop Until k = 10

    Return 0
End Function

我已调用该函数,但文本框仅返回零。

1 个答案:

答案 0 :(得分:1)

您需要找到您使用的网络接口,使用下面的代码创建一个控制台应用程序,您将能够看到哪个接口处于活动状态。

此外,您将无法以这种方式更新UI,您需要使用后台工作程序在文本框中进行滚动更新。

Sub Main()

Dim networkInterfaces As New  System.Diagnostics.PerformanceCounterCategory("Network Interface")
    Dim nics As String() = networkInterfaces.GetInstanceNames()
    Dim bytesSent(nics.Length - 1) As System.Diagnostics.PerformanceCounter
    Dim bytesReceived(nics.Length - 1) As System.Diagnostics.PerformanceCounter
    Dim i As Integer
    For i = 0 To nics.Length - 1
  bytesSent(i) = New System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Sent/sec", nics(i), True) 
  bytesReceived(i) = New System.Diagnostics.PerformanceCounter("Network Interface", "Bytes received/sec", nics(i), True) 
Next 
    'Dim ni As System.Diagnostics.PerformanceCounter 
For i = 0 To nics.Length - 1 
  System.Console.WriteLine(String.Format("     interface {0}: {1} ", i, nics(i))) 
Next 
Do 
        For i = 0 To nics.Length - 1
            System.Console.WriteLine(String.Format("     interface {0}: {1} bytes sent/sec, {2} bytes received/sec.  ", i, bytesSent(i).NextValue, bytesReceived(i).NextValue))
        Next

        System.Console.WriteLine("")
        System.Console.WriteLine("")
        System.Threading.Thread.Sleep(3000)
Loop 

End Sub