SerialPort ReadLine() after Thread.Sleep() goes crazy

Posted by Mat on Stack Overflow See other posts from Stack Overflow or by Mat
Published on 2010-12-27T01:47:08Z Indexed on 2010/12/27 1:53 UTC
Read the original article Hit count: 527

Hi everybody, I've been fighting with this issue for a day and I can't find answer for it. I am trying to read data from GPS device trough COM port in Compact Framework C#. I am using SerialPort class (actually my own ComPort class boxing SerialPort, but it adds only two fields I need, nothing special).
Anyway.. I am running while loop in a separate thread which reads line from the port, analyze NMEA data, print them, catch all exceptions and then I Sleep(200) the thread, cause I need CPU for other threads... Without Sleep it works fine, but uses 100% CPU.. When I dont use Sleep after few minutes the output from COM port looks like this:

GPGSA,A,3,09,12,22,17,15,27,,,,,,,2.6,1.6,2.1*3F
GSA,A,3,09,12,22,17,15,27,,,,,,,2.6,1.6,2.1*3F
A,A,3,09,12,22,17,15,27,,,,,,,2.6,1.6,2.1*3F
,18,12,271,24,24,05,020,24,14,04,326,25,11,03,023,*76
A,3,09,12,22,17,15,27,,,,,,,2.6,1.6,2.1*3F
3,09,12,22,17,15,27,,,,,,,2.6,1.6,2.1*3F
09,12,22,17,15,27,,,,,,,2.6,1.6,2.1*3F
,12,22,17,15,27,,,,,,,2.6,1.6,2.1*3F

as you can see the same message is read few times but cut. I wonder what I'm doing wrong... My port configuration:

port.ReadBufferSize = 4096;  
port.BaudRate = 4800;  
port.DataBits = 8;  
port.Parity = Parity.None;  
port.StopBits = StopBits.One;  
port.NewLine = "\r\n";  
port.ReadTimeout = 1000;  
port.ReceivedBytesThreshold = 100000; 

And my reading function:

private void processGps(){  
    while (!closing)   
    {  
        //reconnect if needed
        try  
        {  
            string sentence = port.ReadLine();  
            //here print the sentence  
            //analyze the sentence (this takes some time 50-100ms)  
        }  
        catch (TimeoutException)  
        {  
            Thread.Sleep(0);  
        }  
        catch (IOException ioex)  
        {  
            //handling IO exception (some info on the screen)  
        }  
    Thread.Sleep(200);  
    }  
}

There is some more stuff in this function like reconnection if the device is lost etc.. but it is not called when the GPS is connected properly.. I was trying

port.DiscardInBuffer();

after some blocks of code (in TimeoutException, after read..)

Did anyone had similar problem? I really dont know what I'm doing wrong.. The only way to get rig of it is removing the last Sleep... Thanks in advance! Best Regards, Mat

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading