简体   繁体   中英

WPF TextBlock Update

Just for academic purposes, im adapting a previous code from windows form to WPF, the thing is that I don't can't understand how the invoke works, hopefully someone can shed me a light while I read some tutorials and explain me what I could do adapt this code.

Everytime someone sends a message on send_click, it sends to a server to which dispatches to all connected sockets. My question is, how do I adapt this code to make the textblock "updatable"? It says it's already being used by another thread (the main thread). This is the code that my application contains. Thanks in advance!

Update #1: This is my first attempt at using the dispatcher invoke http://gyazo.com/42008aacbec2f8494bb7c6c33889d9ad however I'm not understanding the reason behind this walloftext.

 public Lobby()
    {
        InitializeComponent();
        ctThread = new Thread(getMessage);
        ctThread.Start();
        clientSocket.Connect("127.0.0.1", 8888);
        serverStream = clientSocket.GetStream();
    }

    TcpClient clientSocket = new System.Net.Sockets.TcpClient();
    NetworkStream serverStream = default(NetworkStream);
    string readData = null;
    Thread ctThread;


    private void btnSend_Click(object sender, RoutedEventArgs e)
    {
        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtInput.Text);
        serverStream.Write(outStream, 0, outStream.Length);
        serverStream.Flush();
    }

    private void getMessage()
    {
        while (true)
        {
            serverStream = clientSocket.GetStream();
            int buffSize = 0;
            byte[] inStream = new byte[10025];
            buffSize = clientSocket.ReceiveBufferSize;
            serverStream.Read(inStream, 0, buffSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);
            readData = "" + returndata;
            Dispatcher.BeginInvoke(new Action(() =>
                {
                        txtContent.Text = txtContent.Text + Environment.NewLine + " >> " + readData;
                }));
        }
    }          

msg is on its own thread, so UI updates from that function must be marshalled onto the UI thread. You use Dispatcher.BeginInvoke to do this:

Dispatcher.BeginInvoke(new Action(() =>
{
    if (txtContent.Text != null)
    {
        txtContent.Text = txtContent.Text + Environment.NewLine + " >> " + readData;
    }
});

Note that you should consider using a binding instead of directly manipulating the UI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM