VB.Net - 定时器控制冻结应用程序

时间:2017-03-22 00:39:45

标签: vb.net timer

我在vb.net应用程序中添加了一个Timer控件,用于检查网站是启动还是关闭。应用程序中有两个Timer控件。两者都来自System.Windows.Forms.Timer。

有Timer1和Timer2。 Timer1用于执行网站检查。 Timer2只是在表单底部的ToolStrip中显示当前日期和时间。 Timer2在没有显示时间的情况下运行,但是当我启动运行Timer1的网站检查时,应用程序在两次检查后冻结。有时它会运行更长时间,但最终冻结。

我必须从任务管理器中结束任务才能关闭应用程序。我已经在Debugger中测试了这个,并在运行可执行文件之后。我也完全删除了Timer2并进行了测试,但冻结仍然存在。这是我的代码。非常感谢任何帮助。

Imports System


Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        lblStatus.Text = ""
        Timer1.Stop()

        btnStart.Enabled = True
        btnStop.Enabled = False

    End Sub

    Public Function CheckAddress(ByVal URL As String) As Boolean
        Try
            Dim request As WebRequest = WebRequest.Create(URL)
            Dim response As WebResponse = request.GetResponse()
        Catch ex As Exception
            Return False
        End Try
        Return True
    End Function

    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick

        Dim startPoint As Integer = -1

        If CheckAddress(txtAddress.Text).ToString() = True Then
            rtxtResults.AppendText(" -- " & txtAddress.Text & " - Website shows UP at " & tsClock.Text & " - " & vbNewLine)
        ElseIf CheckAddress(txtAddress.Text).ToString() = False Then
            rtxtResults.AppendText(" -- " & txtAddress.Text & " - Website shows DOWN at " & tsClock.Text & " - " & vbNewLine)
        End If

        Do
            startPoint = rtxtResults.Find("Website shows DOWN at", startPoint + 1, RichTextBoxFinds.None)
            If (startPoint >= 0) Then
                rtxtResults.SelectionStart = startPoint
                rtxtResults.SelectionLength = "Website shows DOWN at".Length
                rtxtResults.SelectionColor = Color.Red
            End If
        Loop Until startPoint < 0


    End Sub

    Private Sub Timer2_Tick(sender As System.Object, e As System.EventArgs)
        tsClock.Text = Now()
    End Sub

    Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click

        If txtInterval.Text = "" Then
            MsgBox("Must enter a number")
            Exit Sub
        End If
        lblStatus.ForeColor = Color.Green
        lblStatus.Text = "Running"
        btnStart.Enabled = False
        btnStop.Enabled = True
        Timer1.Interval = Int(txtInterval.Text) * 1000
        Timer1.Start()

    End Sub

    Private Sub btnStop_Click(sender As System.Object, e As System.EventArgs) Handles btnStop.Click
        lblStatus.ForeColor = Color.Red
        lblStatus.Text = "Stopped"
        btnStop.Enabled = False
        btnStart.Enabled = True

        Timer1.Stop()
    End Sub


End Class

1 个答案:

答案 0 :(得分:2)

您的应用程序的用户界面将&#34;冻结&#34;直到Timer1_Tick方法完成。您的Timer1_Tick Do...Loop很可能不会退出。请尝试删除DoLoop行。