我的SerialDataEventHandler只运行一次

时间:2017-04-14 10:23:21

标签: c# event-handling serial-port

我的SerialDataEventHandler存在问题,它只运行一次,让我用以下代码解释一下:

    public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        //init serialport comport
        SerialPort comport = (SerialPort)sender;

        // Shortened and error checking removed for brevity...
        if (!comport.IsOpen) return;
        int bytes = comport.BytesToRead;
        byte[] buffer = new byte[bytes];
        comport.Read(buffer, 0, bytes);
        HandleSerialData(buffer, comport);
        comport.DataReceived -=
            new SerialDataReceivedEventHandler(DataReceivedHandler);
    }

    public void HandleSerialData(byte[] respBuffer, SerialPort comport)
    {
        StringBuilder hex = new StringBuilder(respBuffer.Length * 2);
        foreach (byte b in respBuffer)
            hex.AppendFormat("{0:x2}", b);

        string hex2 = hex.ToString();
        hex2 = hex2.Substring(22, 8);
        Dispatcher.BeginInvoke((Action)(() => { EnOcean_Label.Content = hex2; }));
        Dispatcher.BeginInvoke((Action)(() => { EnOcean2_Label.Content = hex2; }));
    }

所以,我在数据网格中注册我的数据,但这里没关系,我唯一的问题是,我的代码只运行一次,并且需要在第一次调用之后“永远”工作我应该使用哪种函数/方法用于让程序从我的SerialPort获取新数据。

1 个答案:

答案 0 :(得分:1)

您只接收一次数据通知事件,因为您在第一次出现时从DataReceived取消订阅。删除

    comport.DataReceived -=
        new SerialDataReceivedEventHandler(DataReceivedHandler);

来自DataReceivedHandler