2012-03-12 63 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