I have a device that is connected to the computer with a USB cable (Prolific USB to Serial ), I use the following code to read data
(code taken from https://www.vgies.com/a-reliable-serial-port-in-c/)
public class ReliableSerialPort : SerialPort
{
:
:
private void ContinuousRead()
{
byte[] buffer = new byte[4096];
Action kickoffRead = null;
kickoffRead = () =>
{
try
{
BaseStream.BeginRead(buffer, 0, buffer.Length, delegate (IAsyncResult ar)
{
try
{
int count = BaseStream.EndRead(ar);
byte[] dst = new byte[count];
Buffer.BlockCopy(buffer, 0, dst, 0, count);
OnDataReceived(dst);
}
catch (Exception exception)
{
Console.WriteLine($"OptimizedSerialPort exception!\r\n {exception.ToString()}");
}
kickoffRead();
}, null);
}
catch (Exception e)
{
//When disconnecting while accessing BaseStream an InvalidOperationException is raised, we ignore it
}
};
kickoffRead();
}
Every few seconds I also send a message to the device.
After disconnecting the cable from the device (the cable stays connected to the computer) I still get data!!!
i.e. the line int count = BaseStream.EndRead (ar); Returns a number greater than 0.
the data is the message I sent.
What could be the reason?