2012-03-12 55 views
1

我对VB.NET和WPF比较陌生,我有一个基本的线程问题。VB.NET WPF线程

我只想弄清楚如何在使用NavigationService的页面内使用Timer。以下是我有:

Public Class SplashPage 
    Inherits Page 

    Public Sub New(ByVal oData As Object) 

     StartTimer(5000) 

    End Sub 

    Public Sub StartTimer(ByVal iInterval As Double) 

     Dim timeoutTimer As New System.Timers.Timer 

     timeoutTimer.Interval = 5000 
     timeoutTimer.Enabled = True 

     'Function that gets called after each interval 
     AddHandler timeoutTimer.Elapsed, AddressOf OnTimedEvent 

    End Sub 

    Public Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs) 

     If NavigationService.CanGoBack Then 
      NavigationService.GoBack() 
     End If 

     'MessageBox.Show(e.SignalTime) 

    End Sub 

End Class 

的NavigationService.CanGoBack语句导致错误消息:“因为不同的线程拥有它调用线程不能访问此对象”

任何意见或建议,将不胜感激。谢谢!

  • MG

回答

1

这里的问题是,你不能从后台线程触摸UI元素。在这种情况下,Timer.Elapsed事件在后台线程中触发,当您触摸UI时会出错。你需要触摸元素

Private context = SynchronizationContext.Current 
Public Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs) 
    context.Post(AddressOf OnTimerInMainThread, e) 
End Sub 

Private Sub OnTimerInMainThread(state as Object) 
    Dim e = CType(state, ElapsedEventArgs) 
    If NavigationService.CanGoBack Then 
    NavigationService.GoBack() 
    End If 

    MessageBox.Show(e.SignalTime) 
End Sub 
+0

我得到你的代码的第二行这个错误之前,使用SynchronizationContext.Post要回到UI线程:“未设置为一个对象的实例对象引用” – zzMzz 2012-03-13 14:38:16

+0

@MikeG ym不好。我更改了代码以修复该问题 – JaredPar 2012-03-13 17:45:16

+0

感谢您为我的问题Jared提供答案!我还发现System.Windows.Threading.DispatcherTimer完成了我所需要的工作,而没有使用上面定时器的麻烦。 – zzMzz 2012-03-16 17:36:42