我想我知道如何解决这个问题,但如果有人有比我要实施的更好的想法,请告诉我。
我知道,当尝试从另一个线程访问 UI 线程上的控件的属性时需要调用 - 但我遇到了一个事件的问题,它给了我旧的“ The calling thread cannot access this object because a different thread owns it.
”错误。
现在我的印象是UI线程上发生了一个事件,因此这种跨线程异常不应该有问题......这是我的XML:
<MenuItem Header="Search Both" Foreground="Black">
<TextBox
Name="SearchBothBox"
Height="23"
Width="120"/>
这是相关按键事件的代码:
Private Sub SearchBothBox_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles SearchBothBox.KeyDown
If e.Key = Key.Enter Then
Dim SearchThread As New Thread(Sub() Search(Me.SearchBothBox.Text, 1)) <-- Exception occurs here when accessing SearcbhBothBox.Text
SearchThread.Start()
End If
End Sub
无论如何,我将使用调用来拉入字符串。
Dim SearchString As String
Me.Dispatcher.Invoke(New Action(Sub() SearchString = Me.SearchBothBox.Text))
我仍然对为什么我会在这个事件处理程序上得到这个异常感到困惑,我想我会检查是否有更好的方法来处理这种情况。