跨线程操作无效

Hou*_*han 5 vb.net multithreading

即时尝试使用以下代码访问另一个表单上的富文本框:

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
Run Code Online (Sandbox Code Playgroud)

但我得到交叉线程操作无效错误,我认为这样做是因为它错过了window.invokeif语句的一部分.我也尝试替换If window.RichTextBox1.InvokeRequired Then to,If InvokeRequired Then但它会在一个继续循环中被捕获并引发堆栈溢出错误.

谢谢Houlahan

Tim*_*z0r 6

我相信,在第5行,window.Invoke应该改为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
Run Code Online (Sandbox Code Playgroud)