VB.NET [跨线程操作无效:控件 'txtIncomingText' 从线程访问.......]

VB.NET [Cross-thread operation not valid: Control 'txtIncomingText' accessed from a thread........]

我是VB.NET的初学者,请多多包涵

我已经在 VB.NET 中下载了一个多客户端 TCP-IP 套接字服务器-客户端应用程序。服务器听得很好,但客户端遇到以下异常:

"Cross-thread operation not valid: Control 'txtIncomingText' accessed from a thread other than the thread it was created on."

如果你们能帮助我更正代码版本,我将不胜感激。谢谢。

' ------ 客户端代码 ------

Imports System.Windows.Forms
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading

Public Class frmClient

    Inherits Form

    Private Sub frmClient_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private _clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

    Public Sub New()
        InitializeComponent()
    End Sub

    Private receivedBuf As Byte() = New Byte(1023) {}
    Private thr As Thread

    Private Sub ReceiveData(ar As IAsyncResult)
        Dim socket As Socket = DirectCast(ar.AsyncState, Socket)
        Dim received As Integer = socket.EndReceive(ar)
        Dim dataBuf As Byte() = New Byte(received - 1) {}
        Array.Copy(receivedBuf, dataBuf, received)


        ' These two lines encounter an error ->>>>>
        txtIncomingText.Text = (Encoding.ASCII.GetString(dataBuf))
        rbChat.Text = "\nServer: " + txtIncomingText.Text


        _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), _clientSocket)
    End Sub

    Private Sub SendLoop()
        While True
            'Console.WriteLine("Enter a request: ");
            'string req = Console.ReadLine();
            'byte[] buffer = Encoding.ASCII.GetBytes(req);
            '_clientSocket.Send(buffer);

            Dim receivedBuf As Byte() = New Byte(1023) {}
            Dim rev As Integer = _clientSocket.Receive(receivedBuf)
            If rev <> 0 Then
                Dim data As Byte() = New Byte(rev - 1) {}
                Array.Copy(receivedBuf, data, rev)
                lbStt.Text = ("Received: " + Encoding.ASCII.GetString(data))
                rbChat.AppendText(vbLf & "Server: " + Encoding.ASCII.GetString(data))
            Else
                _clientSocket.Close()
            End If
        End While
    End Sub

    Private Sub LoopConnect()
        Dim attempts As Integer = 0
        While Not _clientSocket.Connected
            Try
                attempts += 1
                _clientSocket.Connect(IPAddress.Loopback, 420)
            Catch generatedExceptionName As SocketException
                'Console.Clear();
                lbStt.Text = ("Connection attempts: " + attempts.ToString())
            End Try
        End While
        lbStt.Text = ("Connected!")
    End Sub

    Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
        If _clientSocket.Connected Then

            Dim buffer As Byte() = Encoding.ASCII.GetBytes(txtText.Text)
            _clientSocket.Send(buffer)
            rbChat.AppendText("Client: " + txtText.Text)
        End If
    End Sub

    Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
        LoopConnect()
        ' SendLoop();
        _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), _clientSocket)            Dim buffer As Byte() = Encoding.ASCII.GetBytes("@@" + txtName.Text)
        _clientSocket.Send(buffer)
    End Sub

End Class

嗯,您应该在控件的线程上调用。这是一个快速而肮脏的解决方案

Dim message = Encoding.ASCII.GetString(dataBuf)
txtIncomingText.Invoke(Sub() txtIncomingText.Text = message)
rbChat.Invoke(Sub() rbChat.Text = Environment.NewLine & "Server: " & message)

但是你应该先检查是否需要调用。参见 https://msdn.microsoft.com/en-us/library/ms171728(v=vs.110).aspx

此外,"\n" 不是您在 vb.net 中换行的方式(您是否从 c# 复制了这段代码?)。

并且 + 不是您在 vb.net 中连接字符串的方式( 参见上面的括号 )。