C#写的串口程序,有时打开串口或关闭时出现窗口卡死怎么回事
附代码,应该是DataReceive里面除了问题吧unsafevoidserial_DataReceived(objectsender,SerialDataReceive...
附代码,应该是DataReceive里面除了问题吧
unsafe void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
String recv = "\r\n";
try
{
recv = this.serialPort.ReadLine();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
int n = this.serialPort.BytesToRead;
Byte[] rd_buf = new Byte[n];
this.serialPort.Read(rd_buf, 0, n);
}
Byte[] buf = System.Text.Encoding.Default.GetBytes(recv);
builder.Clear();//清除字符串构造器的内容
builder.Append(Encoding.ASCII.GetString(buf));
this.Invoke((EventHandler)(delegate
{
this.textReceive.AppendText(builder.ToString());
this.textReceive.AppendText("\n");
})); 展开
unsafe void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
String recv = "\r\n";
try
{
recv = this.serialPort.ReadLine();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
int n = this.serialPort.BytesToRead;
Byte[] rd_buf = new Byte[n];
this.serialPort.Read(rd_buf, 0, n);
}
Byte[] buf = System.Text.Encoding.Default.GetBytes(recv);
builder.Clear();//清除字符串构造器的内容
builder.Append(Encoding.ASCII.GetString(buf));
this.Invoke((EventHandler)(delegate
{
this.textReceive.AppendText(builder.ToString());
this.textReceive.AppendText("\n");
})); 展开
若以下回答无法解决问题,邀请你更新回答
2个回答
展开全部
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
byte[] result = new byte[serialPort1.BytesToRead];
serialPort1.Read(result, 0, serialPort1.BytesToRead);
foreach (byte b in result)
{
sb.Append((char)b);
}
AddTextToTxtbox at = new AddTextToTxtbox(addTextToTxtbox);
this.Invoke(at, sb.ToString());
/* this.Invoke((EventHandler)delegate(string msg)
{
this.richTextBox1.AppendText(msg);
},sb.ToString());*/
sb.Clear();
}
private void addTextToTxtbox(string msg)
{
richTextBox1.AppendText(msg);
}
{
byte[] result = new byte[serialPort1.BytesToRead];
serialPort1.Read(result, 0, serialPort1.BytesToRead);
foreach (byte b in result)
{
sb.Append((char)b);
}
AddTextToTxtbox at = new AddTextToTxtbox(addTextToTxtbox);
this.Invoke(at, sb.ToString());
/* this.Invoke((EventHandler)delegate(string msg)
{
this.richTextBox1.AppendText(msg);
},sb.ToString());*/
sb.Clear();
}
private void addTextToTxtbox(string msg)
{
richTextBox1.AppendText(msg);
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
用异步线程
追问
可以大概说下怎么做吗
追答
在新线程里 串口操作,多线程懂不?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询