VB.net中的中断循环

时间:2015-08-25 17:14:32

标签: vb.net

我有一个循环运行,但希望它在按下按钮时停止,并在按下另一个按钮时再次启动。这是我的代码:

Public Class Form1
Private loopon As Boolean
Public Function ping(ByVal server As String) As String
    Dim s As New Stopwatch
    s.Start()
    My.Computer.Network.Ping(server)
    s.Stop()
    Return s.ElapsedMilliseconds.ToString
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    loopon = True
    TextBox1.Text = "Ping results:"
    Do While loopon = True
        TextBox1.AppendText(Environment.NewLine)
        TextBox1.AppendText(ping("server name here"))
    Loop
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    loopon = False
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    TextBox1.Text = String.Empty
    TextBox1.Text = "Ping results:"
    loopon = True
End Sub
End Class

当我尝试运行代码时,通过调试,我的计算机在一段时间后给我一个蓝屏并重新启动。我很确定我搞砸了退出循环。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以使用计时器每隔5秒ping一次(比如说),直到"停止"单击按钮。在表单设计器中,将Timer拖到表单上,然后使用以下代码:

Public Class Form1
    Private stopPing As Boolean

    Public Sub Ping(ByVal server As String)
        Dim s As New Stopwatch
        s.Start()
        My.Computer.Network.Ping(server)
        s.Stop()
        TextBox1.AppendText(Environment.NewLine & s.ElapsedMilliseconds.ToString)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TextBox1.Text = "Ping results:"
        Ping "server name here"
        Timer1.Interval = 5000 'Set timer Interval to 5 seconds
        Timer1.Start
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        stopPing = True
    End Sub

    Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        If stopPing Then Timer1.Stop Else Ping "server name here"
    End Sub
End Class