尝试在计时器内打开新表单实例的交叉线程错误

时间:2015-04-16 05:52:18

标签: vb.net winforms timer

我正在尝试为我的应用程序创建一些通知弹出窗口,并创建了一个淡入淡出的新表单,并且位于我的主表单之上(似乎工作正常)。

我的问题是我有一些代码位于一个timer事件中,每隔一分钟就会进行一些数据检查。根据数据结果,我有时需要显示通知。但是,它导致了我的跨线程错误(这是可以理解的),但我不知道如何解决它。

我想要做的例子(简而言之)是:

Private Sub RefreshData(sender As Object, e As System.Timers.ElapsedEventArgs)
    Try
        MainRefreshTimer.Interval = GetInterval()
        MainRefreshTimer.Start()

        'Do some data checking here...
        If data returns true then
            Dim notify as New frmNewNotification("Some Text", 10) '<== Show some text for 10 seconds then close the form automatically
            notify.Show() '<== Cross Thread Error occurs from this
        End If
    ...

End Sub

1 个答案:

答案 0 :(得分:-1)

我会尝试其中一个想法:

Shorcut :将其放入您的Form_Load

Control.CheckForIllegalCrossThreadCalls = False 

或者,更好,例如:

Private Sub delRefreshData(data as Object)
  If Me.InvokeRequired Then
    ' Invoke(New MethodInvoker(AddressOf delRefreshData)) ' no params
    Invoke(New MethodInvoker(Sub() delRefreshData(data)))
  Else
    'Do some data checking here...
      If data returns true then
       Dim notify as New frmNewNotification("Some Text", 10) 
       notify.Show() '
      End If
  End if

Using InvokeRequired vs control.InvokeRequired

<强>编辑: 为了避免将来被指责为Shorcut,我不得不说 Control.CheckForIllegalCrossThreadCalls不是一个好的建议/解决方案,如下所述:

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on