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

时间:2017-06-01 17:03:29

标签: vb.net multithreading visual-studio sockets visual-studio-2012

我是VB.NET的初学者,请耐心等待。

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

"跨线程操作无效:控制< txtIncomingText'从其创建的线程以外的线程访问。"

如果你们能帮助我修正代码版本,我会很开心。谢谢。

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

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

1 个答案:

答案 0 :(得分:1)

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

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中连接字符串的方式(见上面的括号)。