SerialData.Eof circumstances

后端 未结 1 880
迷失自我
迷失自我 2021-01-02 06:53

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

void DataReceived(object sender, SerialDataReceivedEventArgs e) {
    if (e.Ev         


        
相关标签:
1条回答
  • 2021-01-02 07:25

    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
    }
    
    0 讨论(0)
提交回复
热议问题