Cross thread operation not valid
im trying to access a rich textbox on another form im using the following code to do so:
Private Delegate Sub StringDelegateChat(text As String, window As ChatWindow)
Private Sub AppendTextChatWindows(text As String, window As ChatWindow)
Try
If window.RichTextBox1.InvokeRequired Then
window.Invoke(New StringDelegateChat(AddressOf AppendTextChatWindows), text, window)
Else
window.RichTextBox1.AppendText(text)
window.RichTextBox1.SelectionStart = window.RichTextBox1.Text.Length
window.RichTextBox1.ScrollToCaret()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
but i get the cross th开发者_如何转开发read operation not valid error, i think it does this because it misses out the window.invoke
part of the if statement. i also tried replacing theIf window.RichTextBox1.InvokeRequired Then
to If InvokeRequired Then
but it gets caught in a continues loop and a stack overflow error is thrown.
Thanks Houlahan
I believe, on line 5, window.Invoke
should be changed to window.RichTextBox1.Invoke
.
Private Delegate Sub StringDelegateChat(text As String, window As ChatWindow)
Private Sub AppendTextChatWindows(text As String, window As ChatWindow)
Try
If window.RichTextBox1.InvokeRequired Then
window.RichTextBox1.Invoke(New StringDelegateChat(AddressOf AppendTextChatWindows), text, window)
Else
window.RichTextBox1.AppendText(text)
window.RichTextBox1.SelectionStart = window.RichTextBox1.Text.Length
window.RichTextBox1.ScrollToCaret()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Have you tried:
Private Sub AppendTextChatWindows(text As String, window As ChatWindow)
Try
If window.RichTextBox1.InvokeRequired Then
window.RichTextBox1.BeginInvoke(New StringDelegateChat(AddressOf AppendTextChatWindows), text, window)
Exit Sub
Else
window.RichTextBox1.AppendText(text)
window.RichTextBox1.SelectionStart = window.RichTextBox1.Text.Length
window.RichTextBox1.ScrollToCaret()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Basically, I am asking about BeginInvoke rather than Invoke. Although I would expect, as another poster mentioned, that you should be using the same thing you check the required against to invoke. (ie both window.invokeRequired & window.BeginInvoke or the control)
I cant see any errors in your code. You might want to check for any events that are fired when updating the RichTextbox. They might be causing a cross threading.
As a workaround to your problem, working with objects, you are less likely o encounter cross threading problems.
精彩评论