jcurl / RJCP.DLL.SerialPortStream

SerialPortStream is an independent implementation of System.IO.Ports.SerialPort and SerialStream for better reliability and maintainability. Default branch is 2.x and now has support for Mono with help of a C library.
Microsoft Public License
639 stars 199 forks source link

Does a blocking read byte method exist? #34

Closed wolfen351 closed 7 years ago

wolfen351 commented 7 years ago

Hi there

Please pardon my ignorance, but i'm looking for the simplest possible method (imho) and not finding it - a way to read a byte from the stream when it becomes available. I'm happy to block until the byte arrives.

Please can you point me to such a method?

Thanks!

jcurl commented 7 years ago

There is plenty that I've copied from the MSDN implementation:

To block forever, ensure that ReadTimeout is set to -1.

Cheers, Jason.

wolfen351 commented 7 years ago

Ok, thank you. I was under the impression that these didn't block, that they returned immediately with -1 if data was not available (i'm thinking specificially about ReadByte() here). I found the wiki in the meantime, so all is good :)

jcurl commented 7 years ago

Looking at the code:

public override int ReadByte()
        {
            if (IsDisposed) throw new ObjectDisposedException("SerialPortStream");
            if (m_Buffer == null) return -1;
            if (ReadCheckDeviceError()) return -1;

            if (m_NativeSerial.IsRunning) {
                if (!m_Buffer.Stream.WaitForRead(m_ReadTimeout)) {
                    ReadCheckDeviceError();
                    return -1;
                }
            }
            int value = m_Buffer.Stream.ReadByte();
            if (value != -1) m_ReadTo.Reset(false);
            return value;
        }

the text m_Buffer.Stream.WaitForRead(m_ReadTimeout) should mean it will block until data is available.