最近小了个串口小程序 ,发现在调用 close()方法关闭串口时,程序被挂起.查找了网络资料,网上说这是C#的一个bug.
摸索了半天,结合前人的程序整理出来一段代码,与大家分享.程序只有接收的部分.
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Threading; 10 using System.IO.Ports; 11 12 namespace SerialPort_Controls 13 { 14 public partial class Form1 : Form 15 { 16 //该程序可实现 ,串口数据的获取(读取新的一行) 波特率4800 串口1 17 string data; 18 private delegate void SetTextCallback(string text); 19 Thread threadReceive; 20 bool TestOff = true; 21 public Form1() 22 { 23 InitializeComponent(); 24 } 25 26 private void SynReceiveData(object serialPortobj) 27 { 28 // this.Text = "正在通信!"; 29 while (true) 30 { 31 data = serialPort1.ReadLine(); 32 SetText(data); 33 } 34 } 35 private void button2_Click(object sender, EventArgs e) 36 { 37 if (serialPort1.IsOpen) 38 { 39 threadReceive.Abort(); 40 serialPort1.Close();//关闭端口 41 this.Text = "通信关闭"; 42 } 43 } 44 private void SetText(string text) 45 { 46 // InvokeRequired需要比较调用线程ID和创建线程ID 47 // 如果它们不相同则返回true 48 if (this.textBox1.InvokeRequired) 49 { 50 SetTextCallback d = new SetTextCallback(SetText); 51 this.Invoke(d, new object[] { text }); 52 } 53 else 54 { 55 this.textBox1.Text += text; 56 } 57 } 58 private void button1_Click(object sender, EventArgs e) 59 { 60 try 61 { 62 serialPort1.Open(); 63 //同步阻塞接收数据线程 64 threadReceive = new Thread(new ParameterizedThreadStart(SynReceiveData)); 65 threadReceive.Start(serialPort1); 66 TestOff = false; 67 this.Text = "正在通信"; 68 } 69 catch (Exception ex) 70 { 71 MessageBox.Show("打开失败"+ex.Message); 72 } 73 } 74 } 75 }