SerialPort BaseStream BeginRead never invokes callback

浪子不回头ぞ 提交于 2019-12-11 21:49:48

问题


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.

来源:https://stackoverflow.com/questions/53342386/serialport-basestream-beginread-never-invokes-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!