I think I know how to fix this, but if someone has a better idea than what I'm going to implement, let me know.
I'm aware that when trying to access a property of a control on the UI thread from another thread requires an invoke - but I've run into an issue with an event that is giving me the old "The calling thread cannot access this object because a different thread owns it.
" error.
Now I was under the impression that an event occurs on the UI thread, and as such shouldn't have an issue with this kind of cross thread exception... Here's my XML:
<MenuItem Header="Search Both" Foreground="Black">
<TextBox
Name="SearchBothBox"
Height="23"
Width="120"/>
And here is the code from the related key down event:
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
Anyway, I'm going to pull in the string using an invoke.
Dim SearchString As String
Me.Dispatcher.Invoke(New Action(Sub() SearchString = Me.SearchBothBox.Text))
I'm still confused as to why I would get this exception on this event handler though, and I thought I'd check to see if there is a better way of handling this situation.
Here at this line:
Dim SearchThread As New Thread(Sub() Search(Me.SearchBothBox.Text, 1))
you are trying to access UI control (TextBox.TextProperty) property on thread other than UI thread. Hence the problem.
Event handler do called on UI thread but from it you have started another thread and tried to access UI property from there.