DataReceived 事件处理程序未接收消息

发布于 2024-08-28 04:50:34 字数 656 浏览 6 评论 0原文

我使用下面的代码通过串行端口事件处理程序接收消息。但它没有收到任何信息。我​​没有收到错误。代码在“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里兽 2024-09-04 04:50:34

当从 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

桃酥萝莉 2024-09-04 04:50:34

ReadLine 取决于是否有 NewLine 字符。使用 Read 方法可能会更幸运。另请参阅BytesToRead 属性。

ReadLine depends on having a NewLine character. You might have better luck with the Read method. See also the BytesToRead property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文