0

我在理解应该如何使用 Dispatcher 来帮助我解决从不同线程访问文本框的问题时遇到了一点麻烦。我想要实现的是让线程在从服务器接收数据后附加到聊天框。

Public Class ChatScreen

Public client As Client

Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    client = Application.Current.Properties("Client")
    Me.Title = "ChitChat - " & client.Name

    txtMessage.Focus()

    Dim serverHandler As New ServerHandler(client.clientSocket, client.networkStream, txtChat)
End Sub

Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSend.Click
    client.SendMessage(txtMessage.Text)
End Sub

Private Sub Window_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles MyBase.KeyDown
    If e.Key = Key.Enter Then
        client.SendMessage(txtMessage.Text)
    End If
End Sub

Public Sub AppendToChat(ByVal message As String)
    txtChat.AppendText(">> " & message)
End Sub

Public Class ServerHandler

    Dim clientSocket As TcpClient
    Public networkStream As NetworkStream
    Dim thread As Thread

    Public Sub New(ByVal clientSocket As TcpClient, ByVal networkStream As NetworkStream)
        Me.clientSocket = clientSocket
        Me.networkStream = networkStream
        thread = New Thread(AddressOf ListenForServer)
        thread.Start()
    End Sub

    Public Sub ListenForServer()
        Dim bytesFrom(10024) As Byte
        Dim message As String

        While True
            networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
            message = System.Text.Encoding.ASCII.GetString(bytesFrom)
            message = message.Substring(0, message.IndexOf("$"))

            'AppendToChat <--- This is where I would like to append the message to the text box
        End While
    End Sub
End Class

结束类

4

1 回答 1

0

您可以使用 SynchronizationContext 来执行此操作,将 UI 胎面上下文存储在这样的变量中

Private syncContext As SynchronizationContext
Private Sub frmClient_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
    syncContext = AsyncOperationManager.SynchronizationContext
End Sub

现在创建一个像这样在主 UI 线程上执行的过程

Private Sub AddTextBox()
    ‘Do whatever you want you are in UI thread here

End Sub

来自您在 UI 线程上的后台线程发布请求,如下所示

syncContext.Post(New SendOrPostCallback(AddressOf AddTextBox), Nothing)

你甚至可以传递参数

Private Sub AddTextBox(ByVal argument As Object)
    ‘Do whatever you want you are in UI thread here

End Sub

.....
syncContext.Post(New SendOrPostCallback(AddressOf AddTextBox), objToPass)
于 2013-01-16T12:27:33.753 回答