Incorrect cross thread operation

im trying to access a rich text field in another im form using the following code:

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 see that the cross-flow operation is not a valid error, I think it does this because it skips part of window.invokethe if statement. I also tried replacing If window.RichTextBox1.InvokeRequired Thenwith If InvokeRequired Then, but it gets into the continuation loop and an error occurs.

Thanks Houlahan

+5
source share
3 answers

I believe that in line 5 window.Invokeshould 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
+6
source

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

, BeginInvoke, Invoke. , , , , . (.. window.invokeRequired, window.BeginInvoke )

+3

I do not see errors in your code. You might want to check for any events that fire when the RichTextbox is updated. They can cause transverse threads.

As a workaround to your problem, working with objects, you are less prone to cross-threading problems.

0
source

All Articles