7
votes

I'm using the .Net SerialPort class in C# to read bytes from a port. On receipt of a DataReceived event I check the serial port to see if bytes are available to be read. However, even if bytes are available, the port can take over half a second to read a single byte. Code is roughtly as follows:

...
while(Port.BytesToRead > 0) 
{
    StopWatch.Restart();
    Int32 BytesRead = Port.Read(Read, 0, 1);
    StopWatch.Stop();
    if (StopWatch.ElapsedMilliseconds > 100)
    {
    // Record the time. The stopwatch code
    // was only added after performance issues were observed.
    }
}

Note that the time which I've measured is not the time to read all bytes, rather the time to read a single byte. Frequently I'll receive a DataReceived event and have to wait 0.5 seconds for the first byte to be read.

I've actually tried setting the Port's ReadTimeout property to something smaller to prevent it from sitting there indefinitely, but this property seems to be ignored.

Any help greatly appreciated.

1
It's probably just the .NET runtime going through the Windows API to connect and read under the hood. Sometimes things take longer than expected. I don't know if you ever noticed, but when you connect to a SQL Server from code for the first time, it takes a moment, but subsequent connections are quicker due to Connection Pooling. It wouldn't surprise me to find that something similar happens here.David
I wonder if it's an issue with the device. Have you tried running this code on a different machine/device?M. Dudley
But if it was the device surely I wouldn't get as far as the port reporting that it had bytes to read.user1762339
There are plenty of screwed-up serial port drivers around but this is a bit unusual. If accurate, not posting the code that does the timing was a bad idea. Try another one.Hans Passant
I simply use a StopWatch to peform the timing - I place a StopWatch.Restart() before the read line and a StopWatch.Stop() after the line. If the elapsed time is greater than 100ms I report it.user1762339

1 Answers

4
votes

Turns out that running connected to the Debugger was causing the problem. Running outside of the debugger the maximum time recorded to read a byte was around 20ms, as opposed to up to 700ms when running within (no breakpoints, conditional or otherwise enabled).

Bit of a red herring, as the real cause of the comms problem when running a release build probably lay elsewhere.