Reputation:
I am trying to make a pinging system to ping an IP in my VB windows form. The current pinging system that I use tends to freeze the application when I enter the text in the textbox. I'm sure there is better ways to do this.
Any ideas where I went wrong?
Timer:
Private Sub Timer4_Tick(sender As Object, e As EventArgs) Handles Timer4.Tick
If Timer4.Enabled = True Then
Dim pingreq As Ping = New Ping()
Dim rep As PingReply = pingreq.Send(NsTextBox1.Text)
NsTextBox4.Text = NsTextBox4.Text + Environment.NewLine + ("Reply from " + NsTextBox1.Text + ":" + NsTextBox2.Text + "| time= " + rep.RoundtripTime.ToString() + "ms")
If rep.RoundtripTime = 0 Then
Timer4.Enabled = False
End If
End If
End Sub
Button:
Private Sub NsButton2_Click(sender As Object, e As EventArgs) Handles NsButton2.Click
Timer4.Enabled = True
End Sub
Upvotes: 0
Views: 389
Reputation: 35270
You could get rid of the timer and just await a task that performs your ping right from the button handler, like this:
Private Async Sub NsButton2_Click(sender As Object, e As EventArgs) Handles NsButton2.Click
Dim t = Task(Of PingReply).Run(
Function()
Dim pingreq As Ping = New Ping()
Dim rep As PingReply = pingreq.Send(NsTextBox1.Text)
Return rep
End Function)
Dim result = Await t
NsTextBox4.Text = NsTextBox4.Text + Environment.NewLine +
("Reply from " + NsTextBox1.Text + ":" + NsTextBox2.Text +
"| time= " + result.RoundtripTime.ToString() + "ms")
End Sub
Upvotes: 3