C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
2014-03-05 16:47
309 查看
第一篇文章我相信很多人不看都能做的出来,但是,用过微软SerialPort类的人,都遇到过这个尴尬,关闭串口的时候会让软件死锁。天哪,我可不是武断,算了。不要太绝对了。99.9%的人吧,都遇到过这个问题。我想只有一半的人真的解决了。另外一半的人就睁只眼闭只眼阿弥佗佛希望不要在客户那里出现这问题了。
你看到我的文章,就放心吧,这问题有救了。我们先回顾一下上一篇中的代码
[c-sharp] view plaincopyprint?
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
int n = comm.BytesToRead;
//声明一个临时数组存储当前来的串口数据
byte[] buf = new byte
;
//增加接收计数
received_count += n;
//读取缓冲数据
comm.Read(buf, 0, n);
//清除字符串构造器的内容
builder.Clear();
//因为要访问ui资源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate{...界面更新,略}));
}
private void buttonOpenClose_Click(object sender, EventArgs e)
{
//根据当前串口对象,来判断操作
if (comm.IsOpen)
{
//打开时点击,则关闭串口
comm.Close();//这里就是可能导致软件死掉的地方
}
else
{...}
}
至此,不会再出现关闭死锁问题了。
希望这篇文章能解你的燃眉之急,非常高兴能与读者分享我层遇到,大多数人都遇到的这个问题。如果说的不明白,欢迎讨论。
后续的有关通讯程序底层设计的文章会讲述一个具有丰富扩展性,但有设计简介的万能通讯库,支持网络、蓝牙、串口通讯、并口通讯。但不要指望我都实现出来了,我只是设计出这个框架。
/article/1780787.html
你看到我的文章,就放心吧,这问题有救了。我们先回顾一下上一篇中的代码
[c-sharp] view plaincopyprint?
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
int n = comm.BytesToRead;
//声明一个临时数组存储当前来的串口数据
byte[] buf = new byte
;
//增加接收计数
received_count += n;
//读取缓冲数据
comm.Read(buf, 0, n);
//清除字符串构造器的内容
builder.Clear();
//因为要访问ui资源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate{...界面更新,略}));
}
private void buttonOpenClose_Click(object sender, EventArgs e)
{
//根据当前串口对象,来判断操作
if (comm.IsOpen)
{
//打开时点击,则关闭串口
comm.Close();//这里就是可能导致软件死掉的地方
}
else
{...}
}
[c-sharp] view plaincopyprint? 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.Text.RegularExpressions; namespace SerialportSample { public partial class SerialportSampleForm : Form { private SerialPort comm = new SerialPort(); private StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建,定义到外面。 private long received_count = 0;//接收计数 private long send_count = 0;//发送计数 private bool Listening = false;//是否没有执行完invoke相关操作 private bool Closing = false;//是否正在关闭串口,执行Application.DoEvents,并阻止再次invoke public SerialportSampleForm() { InitializeComponent(); } //窗体初始化 private void Form1_Load(object sender, EventArgs e) { //初始化下拉串口名称列表框 string[] ports = SerialPort.GetPortNames(); Array.Sort(ports); comboPortName.Items.AddRange(ports); comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1; comboBaudrate.SelectedIndex = comboBaudrate.Items.IndexOf("9600"); //初始化SerialPort对象 comm.NewLine = "/r/n"; comm.RtsEnable = true;//根据实际情况吧。 //添加事件注册 comm.DataReceived += comm_DataReceived; } void comm_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (Closing) return;//如果正在关闭,忽略操作,直接返回,尽快的完成串口监听线程的一次循环 try { Listening = true;//设置标记,说明我已经开始处理数据,一会儿要使用系统UI的。 int n = comm.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致 byte[] buf = new byte ;//声明一个临时数组存储当前来的串口数据 received_count += n;//增加接收计数 comm.Read(buf, 0, n);//读取缓冲数据 builder.Clear();//清除字符串构造器的内容 //因为要访问ui资源,所以需要使用invoke方式同步ui。 this.Invoke((EventHandler)(delegate { //判断是否是显示为16禁止 if (checkBoxHexView.Checked) { //依次的拼接出16进制字符串 foreach (byte b in buf) { builder.Append(b.ToString("X2") + " "); } } else { //直接按ASCII规则转换成字符串 builder.Append(Encoding.ASCII.GetString(buf)); } //追加的形式添加到文本框末端,并滚动到最后。 this.txGet.AppendText(builder.ToString()); //修改接收计数 labelGetCount.Text = "Get:" + received_count.ToString(); })); } finally { Listening = false;//我用完了,ui可以关闭串口了。 } } private void buttonOpenClose_Click(object sender, EventArgs e) { //根据当前串口对象,来判断操作 if (comm.IsOpen) { Closing = true; while (Listening) Application.DoEvents(); //打开时点击,则关闭串口 comm.Close(); Closing = false; } else { //关闭时点击,则设置好端口,波特率后打开 comm.PortName = comboPortName.Text; comm.BaudRate = int.Parse(comboBaudrate.Text); try { comm.Open(); } catch(Exception ex) { //捕获到异常信息,创建一个新的comm对象,之前的不能用了。 comm = new SerialPort(); //现实异常信息给客户。 MessageBox.Show(ex.Message); } } //设置按钮的状态 buttonOpenClose.Text = comm.IsOpen ? "Close" : "Open"; buttonSend.Enabled = comm.IsOpen; } //动态的修改获取文本框是否支持自动换行。 private void checkBoxNewlineGet_CheckedChanged(object sender, EventArgs e) { txGet.WordWrap = checkBoxNewlineGet.Checked; } private void buttonSend_Click(object sender, EventArgs e) { //定义一个变量,记录发送了几个字节 int n = 0; //16进制发送 if (checkBoxHexSend.Checked) { //我们不管规则了。如果写错了一些,我们允许的,只用正则得到有效的十六进制数 MatchCollection mc = Regex.Matches(txSend.Text, @"(?i)[/da-f]{2}"); List<byte> buf = new List<byte>();//填充到这个临时列表中 //依次添加到列表中 foreach (Match m in mc) { buf.Add(byte.Parse(m.Value)); } //转换列表为数组后发送 comm.Write(buf.ToArray(), 0, buf.Count); //记录发送的字节数 n = buf.Count; } else//ascii编码直接发送 { //包含换行符 if (checkBoxNewlineSend.Checked) { comm.WriteLine(txSend.Text); n = txSend.Text.Length + 2; } else//不包含换行符 { comm.Write(txSend.Text); n = txSend.Text.Length; } } send_count += n;//累加发送字节数 labelSendCount.Text = "Send:" + send_count.ToString();//更新界面 } private void buttonReset_Click(object sender, EventArgs e) { //复位接受和发送的字节数计数器并更新界面。 send_count = received_count = 0; labelGetCount.Text = "Get:0"; labelSendCount.Text = "Send:0"; } } } 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.Text.RegularExpressions; namespace SerialportSample { public partial class SerialportSampleForm : Form { private SerialPort comm = new SerialPort(); private StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建,定义到外面。 private long received_count = 0;//接收计数 private long send_count = 0;//发送计数 private bool Listening = false;//是否没有执行完invoke相关操作 private bool Closing = false;//是否正在关闭串口,执行Application.DoEvents,并阻止再次invoke public SerialportSampleForm() { InitializeComponent(); } //窗体初始化 private void Form1_Load(object sender, EventArgs e) { //初始化下拉串口名称列表框 string[] ports = SerialPort.GetPortNames(); Array.Sort(ports); comboPortName.Items.AddRange(ports); comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1; comboBaudrate.SelectedIndex = comboBaudrate.Items.IndexOf("9600"); //初始化SerialPort对象 comm.NewLine = "/r/n"; comm.RtsEnable = true;//根据实际情况吧。 //添加事件注册 comm.DataReceived += comm_DataReceived; } void comm_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (Closing) return;//如果正在关闭,忽略操作,直接返回,尽快的完成串口监听线程的一次循环 try { Listening = true;//设置标记,说明我已经开始处理数据,一会儿要使用系统UI的。 int n = comm.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致 byte[] buf = new byte ;//声明一个临时数组存储当前来的串口数据 received_count += n;//增加接收计数 comm.Read(buf, 0, n);//读取缓冲数据 builder.Clear();//清除字符串构造器的内容 //因为要访问ui资源,所以需要使用invoke方式同步ui。 this.Invoke((EventHandler)(delegate { //判断是否是显示为16禁止 if (checkBoxHexView.Checked) { //依次的拼接出16进制字符串 foreach (byte b in buf) { builder.Append(b.ToString("X2") + " "); } } else { //直接按ASCII规则转换成字符串 builder.Append(Encoding.ASCII.GetString(buf)); } //追加的形式添加到文本框末端,并滚动到最后。 this.txGet.AppendText(builder.ToString()); //修改接收计数 labelGetCount.Text = "Get:" + received_count.ToString(); })); } finally { Listening = false;//我用完了,ui可以关闭串口了。 } } private void buttonOpenClose_Click(object sender, EventArgs e) { //根据当前串口对象,来判断操作 if (comm.IsOpen) { Closing = true; while (Listening) Application.DoEvents(); //打开时点击,则关闭串口 comm.Close(); Closing = false; } else { //关闭时点击,则设置好端口,波特率后打开 comm.PortName = comboPortName.Text; comm.BaudRate = int.Parse(comboBaudrate.Text); try { comm.Open(); } catch(Exception ex) { //捕获到异常信息,创建一个新的comm对象,之前的不能用了。 comm = new SerialPort(); //现实异常信息给客户。 MessageBox.Show(ex.Message); } } //设置按钮的状态 buttonOpenClose.Text = comm.IsOpen ? "Close" : "Open"; buttonSend.Enabled = comm.IsOpen; } //动态的修改获取文本框是否支持自动换行。 private void checkBoxNewlineGet_CheckedChanged(object sender, EventArgs e) { txGet.WordWrap = checkBoxNewlineGet.Checked; } private void buttonSend_Click(object sender, EventArgs e) { //定义一个变量,记录发送了几个字节 int n = 0; //16进制发送 if (checkBoxHexSend.Checked) { //我们不管规则了。如果写错了一些,我们允许的,只用正则得到有效的十六进制数 MatchCollection mc = Regex.Matches(txSend.Text, @"(?i)[/da-f]{2}"); List<byte> buf = new List<byte>();//填充到这个临时列表中 //依次添加到列表中 foreach (Match m in mc) { buf.Add(byte.Parse(m.Value)); } //转换列表为数组后发送 comm.Write(buf.ToArray(), 0, buf.Count); //记录发送的字节数 n = buf.Count; } else//ascii编码直接发送 { //包含换行符 if (checkBoxNewlineSend.Checked) { comm.WriteLine(txSend.Text); n = txSend.Text.Length + 2; } else//不包含换行符 { comm.Write(txSend.Text); n = txSend.Text.Length; } } send_count += n;//累加发送字节数 labelSendCount.Text = "Send:" + send_count.ToString();//更新界面 } private void buttonReset_Click(object sender, EventArgs e) { //复位接受和发送的字节数计数器并更新界面。 send_count = received_count = 0; labelGetCount.Text = "Get:0"; labelSendCount.Text = "Send:0"; } } }
至此,不会再出现关闭死锁问题了。
希望这篇文章能解你的燃眉之急,非常高兴能与读者分享我层遇到,大多数人都遇到的这个问题。如果说的不明白,欢迎讨论。
后续的有关通讯程序底层设计的文章会讲述一个具有丰富扩展性,但有设计简介的万能通讯库,支持网络、蓝牙、串口通讯、并口通讯。但不要指望我都实现出来了,我只是设计出这个框架。
/article/1780787.html
相关文章推荐
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ? .
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?(转帖)
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?
- 为什么C#串口程序在关闭串口时候会死锁
- C# 串口程序在关闭串口时候会死锁