0

我需要使用从串行端口接收到的字符串更新 Windows 窗体标签。我已经编写的代码有两个问题。

因为串口的读取需要另一个线程,所以我使用委托方法来更新标签文本。

第一个问题是当我启动程序时表单窗口不会打开(当我不调用时它会打开initSerialPort()Form1_Load()

Debug.Write(message)第二个问题是我打电话时_self.SetText(message)似乎没有到达Read()。当我注释掉_self.SetText(message)它时,它会记录消息,但也不会打开表单窗口,因为initSerialPort()它被调用了Form1_Load()

我是 C# 的菜鸟,你知道的;)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        delegate void SetTextCallback(string text);

        private static SerialPort _serialPort;
        private static Boolean _continue;
        private static StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        private static Thread readThread = new Thread(Read);
        private static Form1 _self;
        private static Label _lbl;

        public Form1()
        {
            InitializeComponent();
            _self = this;

            _lbl = label1;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            initSerialPort();
        }

        public void setMessage(string mes)
        {
            label1.Text = mes;
        }

        private static void initSerialPort()
        {
            // Create a new SerialPort object with default settings.
            _serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);

            // Set the read/write timeouts
            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort.Open();
            _continue = true;
            readThread.Start();

            readThread.Join();
            _serialPort.Close();
            _serialPort = null;
        }

        public static void Read()
        {
            Debug.Write("testread");
            while (_continue)
            {

                try
                {
                    String message = _serialPort.ReadLine();

                    _self.SetText(message);

                    Debug.Write(message);


                }
                catch (TimeoutException) { }

            }
        }

        private void SetText(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.label1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.label1.Text = text;
            }
        }
    }
}
4

1 回答 1

0

不要Join对您创建的新线程。这将阻塞线程,直到您的Read方法完成,这意味着它永远不会完成。

于 2012-06-12T15:48:54.453 回答