如何在不冻结VB的情况下将ping系统转换为IP?

时间:2016-12-28 21:02:33

标签: vb.net textbox ping

我正在尝试建立一个ping系统来ping我的VB窗体中的IP。当我在文本框中输入文本时,我使用的当前ping操作系统会冻结应用程序。我确信有更好的方法可以做到这一点。

我出错的任何想法?

计时器:

 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

按钮:

 Private Sub NsButton2_Click(sender As Object, e As EventArgs) Handles NsButton2.Click

    Timer4.Enabled = True

End Sub

1 个答案:

答案 0 :(得分:3)

你可以摆脱计时器,等待从按钮处理程序执行ping操作的任务,如下所示:

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