(*The Chinese annotation is not important* The English annotation is what I hope you to pay attention to)
this is the assertion
private SerialPort comm = new SerialPort();
this is the code of function"comm_DataReceived(object sender, SerialDataReceivedEventArgs e)"
comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
n = comm.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
buf = new byte[n];//声明一个临时数组存储当前来的串口数据
// received_count += n;//增加接收计数
comm.Read(buf, 0, n);//读取缓冲数据
builder.Clear();//清除字符串构造器的内容
// this.Invoke(interfaceUpdataHandle, new string[] { Encoding.UTF8.GetString(buf) });
//因为要访问ui资源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate
{
//The intermediate code omitted here
}), new string[] { Encoding.UTF8.GetString(buf) });
}
catch (Exception ex)
{
MessageBox.Show("请不要频繁开关串口");
}
}
this is the code of function“buttonOpenClose_Click(object sender, EventArgs e)”
private void buttonOpenClose_Click(object sender, EventArgs e)
{
this.buttonOpenClose.Enabled = false;
this.Invoke((EventHandler)(delegate
{
//根据当前串口对象,来判断操作
if (comm.IsOpen)
{
//打开时点击,则关闭串口
comm.Close(); //////****HERE****!!!!!!HERE , The program sometimes will stop here when I click the button T_T
}
else
{
//关闭时点击,则设置好端口,波特率后打开
try
{
comm.PortName = comboPortName.Text;
comm.BaudRate = int.Parse(comboBaudrate.Text);
comm.Open();
}
catch (Exception ex)
{
//捕获到异常信息,创建一个新的comm对象,之前的不能用了。
comm = new SerialPort();
//现实异常信息给客户。
MessageBox.Show(ex.Message);
}
}
//设置按钮的状态
buttonOpenClose.Text = comm.IsOpen ? "关闭串口" : "打开串口";
}));
this.buttonOpenClose.Enabled = true;
}
Thanks for your any answer. GOD BLESS YOU ^_^