C# SerialPort DataReceived Event
本文关键字:Event DataReceived SerialPort | 更新日期: 2023-09-27 18:15:39
我正在监听串行端口的5字节信息。这5个字节是投票的完整答案所需的。我的代码监听serialport data_received事件并检查testoread。有时,事件会触发,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());
}
您可以设置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
};
请注意,您应该在打开端口后连接事件处理程序,
这是为了防止某些平台上的已知问题阻止事件
根据SerialPort.cs的参考源,是的,DataReceived
事件可以在BytesToRead
为0时触发,如果内部流的DataRecieved
事件被触发并且事件参数具有EventType == SerialData.Eof
。如果是这种情况,则不考虑BytesToRead
的大小。
内部流的DataReceived
事件处理程序CatchReceivedEvents的相关片段:
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
...