Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

c# - SerialData.Eof circumstances

In my SerialPort.DataReceived event handler, I am checking for SerialData.Eof:

void DataReceived(object sender, SerialDataReceivedEventArgs e) {
    if (e.EventType == SerialData.Eof)
        throw new NotImplementedException("SerialData.Eof");
    // ... Read
}

In my entire development up to this point, I have never hit this exception. But today, when working on a different piece of the protocol, it hit.

My question is, what exactly does SerialData.Eof mean? MSDN says:

The end of file character was received and placed in the input buffer.

I'm dealing with binary data. What is the "end of file character"?


This MSDN Forum Post states that

the DCB.EofChar member always gets initialized to 0x1A (Ctrl+Z)

In the reference sources for the SerialStream class, at line 1343, we see that indeed:

dcb.EofChar = NativeMethods.EOFCHAR;

And in Microsoft.Win32.NativeMethods:

internal const byte EOFCHAR = (byte) 26; 

So does this mean anytime my device sends an 0x1A byte, that I will get a SerialData.Eof event? If that is the case, should I just stop testing for it altogether?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My original analysis in that MSDN post was correct. However, the reference source reveals the answer, from SerialStream.cs:

dcb.EofChar = NativeMethods.EOFCHAR;

//OLD MSCOMM: dcb.EvtChar = (byte) 0;
// now changed to make use of RXFlag WaitCommEvent event => Eof WaitForCommEvent event
dcb.EvtChar = NativeMethods.EOFCHAR;

Ugh, they used the DCB's EvtChar setting to detect a Ctrl+Z. This was a Really Bad Idea, given that there's no way to change it and a 0x1a byte value can certainly appear in a binary protocol. In practice this almost always comes to a good end since there will be something to read when the event fires. Nevertheless, there's now a race condition that can fire another event, this time SerialData.Chars, with nothing to read since the previous event caused all bytes to be read. Which will make the Read() call block until a byte is available. Which usually works out but does increase the odds that the Close() call deadlocks. A chronic SerialPort problem.

The proper way to deal with this is:

void DataReceived(object sender, SerialDataReceivedEventArgs e) {
    if (e.EventType == SerialData.Eof) return;
    // ... Read
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...