Dispatcher.Invoke并从另一个线程访问文本框

时间:2013-01-16 08:25:08

标签: vb.net

我在理解如何利用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

结束班

1 个答案:

答案 0 :(得分: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)