Loop ping and computer status by the network

Viewed 81

I've got a very basic program which use the IP or Hostname of a computer on the network and ping it in order to know if the computer is online or offline by doing a scan every 10 sec and can be started and stopped by a button, and the loop is making the program freeze.

note: The program is still in development.

GUI

Public Class PingerFrm

Dim WorkBool As Boolean
Dim StateStr As String
Dim IPStr As String

Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click

    WorkBool = True
    IPStr = IPTxtBox.Text

    Do While WorkBool = True

        If My.Computer.Network.Ping(IPStr) Then
            StateStr = ("Online")
        Else
            StateStr = ("Offline")
        End If

        StateLbl.Text = StateStr

        Threading.Thread.Sleep(10000)

    Loop

End Sub

Private Sub StopBtn_Click(sender As Object, e As EventArgs) Handles StopBtn.Click
    WorkBool = False
End Sub

End Class

Does anyone see what I'm doing wrong or have any ideas ?

1 Answers

The problem is that you have the UI in a busy loop. Take a look at this

Private Async Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click

    WorkBool = True
    IPStr = IPTxtBox.Text

    If Net.IPAddress.TryParse(IPStr, Nothing) Then
        Dim t As Task
        t = Task.Run(Sub()
                         Dim stateCHGD As Boolean = False
                         StateStr = ""
                         Do While WorkBool
                             If My.Computer.Network.Ping(IPStr) Then
                                 If StateStr <> "Online" Then
                                     stateCHGD = True
                                     StateStr = "Online"
                                 End If
                             Else
                                 If StateStr <> "Offline" Then
                                     stateCHGD = True
                                     StateStr = "Offline"
                                 End If
                             End If
                             If stateCHGD Then
                                 stateCHGD = False
                                 Me.BeginInvoke(Sub()
                                                    StateLbl.Text = StateStr
                                                End Sub)
                             End If
                             Threading.Thread.Sleep(10000)
                         Loop
                     End Sub)
        Await t
    End If
End Sub
Related