Dispatcher.Invoke and access to a text field from another thread

I am having trouble understanding how I should use the Dispatcher to help me solve my problem of accessing a text field from another thread. What I'm trying to achieve is to add a stream to the chat window after receiving data from the server.

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 

Final class

0
source share
1 answer

You can use SynchronizationContext to do this. Store the UI tread context in a variable like this

 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 

Now create a procedure to execute in the main user interface thread, for example

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

Your request to send a background thread to a UI thread like this

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

you can even pass arguments as well

 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) 
0
source

Source: https://habr.com/ru/post/944756/


All Articles