通过http://topic.csdn.net/t/20051102/19/4367443.html中的例子,现在能打开串口进行数据的发送,但是接受的时候遇到问题了,请高手指点。我是这样写的,先定义一个线程,然后点击一个按钮后初始化这个线程,此线程就是不停的读取串口,如果有数据则读出来,没有数据将线程sleep,读完数据后,再用一个按钮去触发该线程的终止,问题是,我终止该线程后,就不能对串口进行操作了,点关闭串口的时候程序死掉。程序代码如下:
//触发读串口线程
private void btnStartRead_Click(object sender, EventArgs e)
        {
            if (commPort.Opened) {
                readThread = new Thread(new ThreadStart(this.ReceiveThread));
                readThread.Name = "commPortReceive";
                readThread.Priority = ThreadPriority.AboveNormal;
                readThread.Start();
                btnStartRead.Enabled = false;                
            }
            else
            {
                MessageBox.Show("串口没有打开!", "通讯错误");
            }
        }//线程调用的方法
private void ReceiveThread()
        {
            while(true){
                byte[] readByte = commPort.Read(2);
                String readStr = System.Text.Encoding.ASCII.GetString(readByte);
                if (readThread!=null && readStr!="")
                {
                    SetText(readStr);
                }else{
                    Thread.Sleep(20);
                }
            }
        }//终止线程
private void btnEndRead_Click(object sender, EventArgs e)
        {
            if (readThread != null)
            {
                readThread.Abort();
                readThread.Join(20);
                readThread = null;
                btnStartRead.Enabled = true;
            }
        }

解决方案 »

  1.   

    线程规划不好,需要在ReceiveThread增加关闭的信号量,例如bool类型的
    参看
    http://blog.csdn.net/Knight94/archive/2006/08/24/1111267.aspx
      

  2.   

    直接用vs2005,带有SerialPort类的。
      

  3.   

    to Knignt94
    引入开关变量后果然可以了,从你的blog也学到不少东西,谢谢。to wuyazhe
    我开始是用的2005自带的那个类,在两台电脑之间也调试通了,但是通过linux的终端远程登陆到windows(通过串口映射)后,再通过软件打开终端上的串口就出错,所以只能寻求API了