SerialPort BaseStream BeginRead never invokes callback

425 views Asked by At

I have a SerialPort object I know is configured correctly because I can send data to the port and the DataReceived event is properly raised. However, when I try the solution presented in How to use SerialPort class more reliably which suggests using calls to BeginRead instead of the DataReceived event, my async callback is never invoked, and the call to BeginRead appears to "hang".

        byte[] buffer = new byte[4096];

        void KickoffRead()
        {
            _serialPort.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate (IAsyncResult ar)
            {
                try
                {
                    var actualLength = _serialPort.BaseStream.EndRead(ar);
                    var received = new byte[actualLength];
                    Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
                    DataReceived?.Invoke(received);
                }
                catch (IOException)
                {
                    // nothing yet
                }

                KickoffRead();
            }, null);
        }

        KickoffRead();  

I've tried calling KickoffRead immediately after opening the port, from the DataReceived event, and from a separate thread - none of that makes any difference. I've also tried changing the buffer size to 1 thinking it was waiting for a full buffer - no luck. Further, when I attempt to stop the debugger it hangs and must be forcefully terminated.

I am doing my testing using virtual serial ports (Free Virtual Serial Ports software) but that works just fine when I used DataReceived instead of BeginRead, so I discounted that as the source of the problem.

0

There are 0 answers