应用程序在执行TimerCallback函数时结束

时间:2015-02-18 07:23:47

标签: vb.net winforms

我试图在VB.NET(4.0)中创建一个非常基本的调度程序应用程序。有一个表单,按钮和标签。那么我想要发生的是在10秒之后必须更改标签文本。所以这就是我做过的事情。

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim t As Timer
    t = New Timer(New TimerCallback(AddressOf timerevent))
    Dim scheduledTime As DateTime = DateTime.MinValue
    scheduledTime = DateAdd(DateInterval.Second, 10, DateTime.Now)
    Dim timespan As TimeSpan = scheduledTime.Subtract(DateTime.Now)

    Dim dueTime As Integer = Convert.ToInt32(timespan.TotalMilliseconds)
    t.Change(dueTime, Timeout.Infinite)

End Sub
Private Sub timerevent(e As Object)
    Try
        Label1.Text = Now.ToString
    Catch ex As Exception
        Label1.Text = ex.Message
    End Try

End Sub

但问题是时间安排在10秒内正确触发,但应用程序立即停止执行或结束。我不知道为什么会这样。

1 个答案:

答案 0 :(得分:1)

您正在使用System.Threading.Timer,它会在ThreadPool主题中触发回调。

在回调中你正在更新UI - 这将导致InvalidOperationException。同意;你有一个try / catch来捕获异常但是你再次在catch块中犯了同样的错误。没人能救你。

您只需使用System.Windows.Forms.Timer来解决问题。这将有效,因为winforms Timer将在UI线程中触发Tick事件。

Know the difference between Timers in .Net framework