DataReceived 事件处理程序未接收消息
我使用下面的代码通过串行端口事件处理程序接收消息。但它没有收到任何信息。我没有收到错误。代码在“string msg = comport.Readline()
”中中断,我做错了什么吗?
public partial class SerialPortScanner : Form
{
private SerialPort comPort = new SerialPort();
public SerialPortScanner()
{
InitializeComponent();
comPort.Open();
comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
}
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (comPort.IsOpen == true)
{
string msg = comPort.ReadLine();
MessageBox.Show(msg);
}
}
}
I'm using the below code to receive the messages using serial port event handler. But it dosent receives any.I am not getting errors. The code breaks in "string msg = comport.Readline()
" Am i doing something wrong ?
public partial class SerialPortScanner : Form
{
private SerialPort comPort = new SerialPort();
public SerialPortScanner()
{
InitializeComponent();
comPort.Open();
comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
}
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (comPort.IsOpen == true)
{
string msg = comPort.ReadLine();
MessageBox.Show(msg);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当从 SerialPort 对象接收到数据时,将在辅助线程上引发 DataReceived 事件。由于此事件是在辅助线程而不是主线程上引发的,因此尝试修改主线程中的某些元素(例如 UI 元素)可能会引发线程异常。
来源:检查这个
The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception.
Source : Check this
ReadLine
取决于是否有NewLine
字符。使用Read
方法可能会更幸运。另请参阅BytesToRead
属性。ReadLine
depends on having aNewLine
character. You might have better luck with theRead
method. See also theBytesToRead
property.