C # virtual serial port timeoutexception on write

I have a problem with virtual serial ports in C #: when I call the Write function, it automatically throws a TimeOutException, but the client receives the data.

This only happens with virtual ports (I am using free virtual serial ports from HDDSoftware with a COM12 ↔ COM13 bridge). I am opening COM12 with Visual Studio and COM13 with Hercules. The application throws a timeout exception, but Hercules gets the message.

It doesn't matter if you set 1000ms or 1,000,000ms read / write timeout.

Thank!!

        using (SerialPort port = new SerialPort("COM13"))
        {
            // configure serial port
            port.BaudRate = 9600;
            port.DataBits = 8;
            port.Parity = Parity.None;
            port.StopBits = StopBits.One;
            port.Open();

            port.ReadTimeout = 10000;

            byte[] buffer = Encoding.ASCII.GetBytes("HELLO WORLD");

            try
            {
                port.Write(buffer, 0, buffer.Length);
            }
            catch(TimeoutException)
            {
                Console.WriteLine("Write timeout");
            }

            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
            try
            {
                byte[] buf = new byte[100];
                port.Read(buf, 0, 1);
            }
            catch(IOException)
            {
                Console.WriteLine("Read timeout");
            }
            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
        }

      

After a few tests (putting Write in a try-catch), the Read operation also throws TimeOutException instantly.

This is what I get when I run the test. Assumed: 12:16:06 (Read timeout) 12:16:16

enter image description here

+3


source to share


2 answers


As Hans Passant said, this is a problem with the Virtual COM software. I tried with Eltima Software's Virtual Serial Port and it worked fine!



0


source


   port.Write(buffer, offset, count);

      

It is up to the device driver how to implement this. But everything I know follows the rule that a basic call to WriteFile () allows * lpNumberOfBytesWritten <nNumberOfBytesToWrite to return. Or, to put it another way, a record is not "transactional."



The decent mental model is that Write () writes one byte from the buffer at a time, countdown time. At some point, completely unpredictable, when, writing another byte, it will stop when the driver's transfer buffer is full and cannot store another byte. Ultimately, the exception is triggered.

Thus, part of the buffer will still go to the other end. You cannot tell which part of the SerialPort class. Timeout is a gross communication error that can be difficult to recover from. If it's a show stopper, then you need to think about writing one byte at a time (thin, serial ports are slow) or pay attention to WriteBufferSize - BytesToWrite to check if the buffer is ok and implement your own timeout.

+2


source







All Articles