C#SerialPort DataReceived事件

时间:2014-07-30 23:38:35

标签: c#

我正在收听5字节信息的串口。轮询的完整答案需要5个字节。我的代码侦听serialport data_received事件并检查bytesToRead。有时,事件将触发并且bytesToRead为0.仅当数据可用时才触发事件吗?

public SerialPort wheel = new SerialPort();
public void wheel_DataReceived(object sender, EventArgs e)
{
    if (wheel.BytesToRead < 5)
    {
        wheelRetry += 1;
        Log("Wheel Data Received: " + wheel.BytesToRead.ToString() + 
            " bytes. Need 5 bytes. Attempt #: " + wheelRetry.ToString());
    }

2 个答案:

答案 0 :(得分:0)

您可以设置ReceivedBytesThreshold属性:

var port = new SerialPort();
port.Open();    

//Only raise the event if 5 bytes have been received
port.ReceivedBytesThreshold = 5;

port.DataReceived += (s, e) =>
{
    //Handle the data
};

请注意,您应该在打开端口后挂钩事件处理程序,
这是为了防止某些平台上的已知问题阻止事件发生 如果它在港口被打开之前被连接起来了。

答案 1 :(得分:0)

根据reference source for SerialPort.cs,是的,DataReceived事件可以在BytesToRead为0时触发, 如果 内部流& #39; s DataRecieved事件被触发,事件args有EventType == SerialData.Eof。如果是这种情况,那么BytesToRead的大小就不会被考虑在内。

来自CatchReceivedEvents的相关摘录,内部流的DataReceived事件处理程序:

bool raiseEvent = false;
try {
    raiseEvent = stream.IsOpen && (SerialData.Eof == e.EventType || BytesToRead >= receivedBytesThreshold);    
}
catch {
    // Ignore and continue. SerialPort might have been closed already! 
}
finally {
    if (raiseEvent)
        eventHandler(this, e);  // here, do your reading, etc. 
}

您可以修改您的事件处理程序,如@elgonzo建议的那样,以便您可以查看EventType

public void wheel_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    if(e.EventType == SerialData.Eof) //return? possibly nothing to read
...