首页 > 解决方案 > 使用 .Net Compact/Windows CE 从线程中的数据设置标签文本

问题描述

我似乎无法找到有关如何执行此操作的可靠信息来源。我正在做的事情的细分。我有一个服务器/客户端正在运行,它在一个线程上运行。收到信息后,我需要将该信息放入标签中。

要完全清楚,我想在标签中显示收到的消息。

我听课的代码:

        public void receiveMessage(IAsyncResult ar)
    {
        //read from client
        int bytesRead;
        try
        {
            lock (_client.GetStream())
            {
                bytesRead = _client.GetStream().EndRead(ar);
                //Console.WriteLine(ASCIIEncoding.ASCII.GetString(data, 0, bytesRead));
            }
            //if client has disconnected
            if (bytesRead < 1)
                return;
            else
            {
                //get the message sent
                string messageReceived =
                    ASCIIEncoding.ASCII.GetString(data, 0, bytesRead);   
                if (frmMain.InvokeRequired)
                {
                    frmMain.UpdateData(messageReceived);
                }
            }
            //continue reading from client
            lock (_client.GetStream())
            {
                _client.GetStream().BeginRead(
                    data, 0, _client.ReceiveBufferSize,
                    receiveMessage, null);

            }
        }
        catch (Exception ex)
        {

        }
    }

frmMain.UpdateData 中的代码:

        public void UpdateData(string text)
    {
        if (InvokeRequired)
        {
            this.Invoke(new Action<string>(UpdateData), new object[] { text });
            return;
        }
        stat_bar.Text = text;
    }

这在普通的桌面 win 表单应用程序上运行良好。但我需要在 WindowsCE/.NetCompact 框架内做一些事情。

标签: c#.netcompact-frameworkwindows-ce

解决方案


要从另一个非 GUI 线程更新 GUI 元素,您需要使用 Delegate 和 Invoke。我总是使用这种模式:

    delegate void SetTextCallback(string text);
    public void addLog(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.txtLog.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(addLog);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            if (txtLog.Text.Length > 2000)
                txtLog.Text = "";
            txtLog.Text += text + "\r\n";
            txtLog.SelectionLength = 0;
            txtLog.SelectionStart = txtLog.Text.Length - 1;
            txtLog.ScrollToCaret();
        }
    }

您可以对所有类型的参数和元素执行此操作。


推荐阅读