views:

3721

answers:

4

I am just reviewing some code I wrote to communicate with the serial port in C# on CF2.0. I am not using DataReceived event since it's not reliable. MSDN states that:

The DataReceived event is not gauranteed to be raised for every byte received. Use the BytesToRead property to determine how much data is left to be read in the buffer.

I poll the port with read() and have a delegate that processes the data when it is read. I also read somewhere that "polling is bad"(no explanation given).

Any ideas why polling might be bad? aside from the usual threading cautions - I have a separate thread (background thread) that polls the port, the thread is exited after the data is read, all tested and works well.

+5  A: 

The way I read that, you might get one event for multiple bytes, rather than one event per byte. I would still expect to get an event when data is ready, and not have it "skip" some bytes entirely.

I've always used this event, and have not had any trouble with it.

Jon B
Absolutely, this is my experience also.
Andy
+3  A: 

Conventional wisdom has it that "polling is bad" because it often ends up being a CPU-bound process. If blocking I/O is used instead, then the CPU is available for other processes until the event happens.

That said, it is usually possible to set things up so that a poll waits for a (short) timeout before returning when no characters are available. If a suitable timeout is chosen, then your simple polling loop uses significantly less CPU time, and other processes also get to run.

I haven't used serial ports from C# at all, but I am going to hazard a guess that what the documentation meant by

The DataReceived event is not guaranteed to be raised for every byte received. Use the BytesToRead property to determine how much data is left to be read in the buffer.

is that you can't expect to get one event per character. It might under some circumstances deliver the event with more than one character available. Simply retrieve all the available characters in your event handler, and all will be well.

Edit: Doing a blocking call on a reader thread might be the best answer overall. It isn't polling per se since the thread is blocked until characters arrive. You might need to tune the buffer sizes and some of the serial port settings if you need to process the data as it arrives rather than in fixed sized chunks.

RBerteig
thanks i guess it makes sense. I am not blocking the CPU. In my app the user should be able to either capture the value from the device or manually type it in. When either happens, polling thread is exited.
gnomixa
A: 

poll will slow-down your system

vitaly.v.ch
A: 

I'm pretty sure the underlying serial port driver code is interrupt driven, even when using the blocking Read call.

thomask