使用计时器更新表单 - VB.Net

时间:2014-02-11 10:10:38

标签: vb.net multithreading forms timer

我想在表单上显示我的应用程序方面的状态。

我尝试在表单中添加一个计时器。计时器每10秒运行一次并检查数据库的特定状态,然后根据状态更改表单上的元素。

这适用于更改菜单项的颜色,但是当我尝试在窗体上显示图像(in)时,会出现跨线程错误。

我应该使用计时器,背景工作者还是别的什么?

有人有一些基本的代码可以优雅地完成这项工作吗?

Private WithEvents tmrMain As New System.Timers.Timer(10000)

Private Sub frmMaster_Load(sender As Object, e As EventArgs) Handles Me.Load
    tmrMain.Enabled = True
    tmrMain.Start()
End Sub

Private Sub tmrMain_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles tmrMain.Elapsed
    Dim TRunning As Boolean = True

        TRunning = BTools.CheckImportRunningStatus '' This gets the on/off status from the DB

        If TRunning Then
            miFileMYOBImport.ForeColor = Color.Red '' Change menu color
            pbMYOBDownload.Visible = True '' Make image visible
        Else
            miFileMYOBImport.ForeColor = Color.DarkGreen
            pbMYOBDownload.Visible = False
        End If
End Sub

1 个答案:

答案 0 :(得分:0)

尝试:

Private Sub MakeImageVisible(ByVal control As Control, ByVal visible As Boolean)
    If control.InvokeRequired Then
        control.BeginInvoke(New Action(Of Control, Boolean)(AddressOf MakeImageVisible), control, visible)
    Else
        control.Visible = visible
    End If
End Sub

Private Sub tmrMain_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles tmrMain.Elapsed
    Dim TRunning As Boolean = True

    TRunning = BTools.CheckImportRunningStatus '' This gets the on/off status from the DB

    If TRunning Then
        miFileMYOBImport.ForeColor = Color.Red '' Change menu color
    Else
        miFileMYOBImport.ForeColor = Color.DarkGreen
    End If

    MakeImageVisible(pbMYOBDownload, TRunning) ' Make image visible or invisible
End Sub