Tuesday, June 20, 2006 8:40 PM
Geoff
Tiny problem in the serial port solution
Just when you think you have it all covered. I was testing the
solution to the serial port issue I wrote about a couple of days ago.
When I ran the code, the CPU pegged at 100%. When I went back to the code it hit me like the proverbial metric ton of bricks. Have a look at this routine:
private string PeekResponseLine()
{
while (true)
{
string bufferCopy = string.Empty;
lock (incomingBuffer)
{
bufferCopy = incomingBuffer;
}
int length = bufferCopy.IndexOf("\r\n");
if (length > -1)
{
if (bufferCopy.Contains(GsmResponses.MessageTextWanted))
{
length = GsmResponses.MessageTextWanted.Length;
}
else if (bufferCopy.Contains(GsmResponses.MessageReceived))
{
length = bufferCopy.IndexOf("\r\n", GsmResponses.MessageReceived.Length);
if (length > -1)
length += 2;
}
else
length += 2;
if (length > -1)
{
string response = bufferCopy.Substring(0, length);
return response;
}
}
}
}What do you notice based on what I've told you about the CPU utilisation? It struck me pretty much straight away. The
while(true) {} loop will just sit there iterating, waiting for a CRLF to come. This is terribly shoddy work on my part. Of course I know you shouldn't poll. I left the loop there, but added an AutoResetEvent that is triggered off data arriving from the serial port. That way, the loop only iterates when there's a reason to.
The result? CPU utilisation went from 100% to 1%. It's not every day you get a perf increase like that. Even if it is your own stupid fault...