Event Example

Jan 8, 2016 at 10:29 PM
Do you have an example of the correct way to retrieve using the DataRecieved Event?
Jan 11, 2016 at 3:36 AM
Edited Jan 11, 2016 at 3:36 AM
It should be done the same way it works in the .NET framework. Once the event triggers, Just Read() and process all available data.

Under the hood, there's the main thread that does the IO (CommOverlappedIo). When data is received, it raises the DataReceived event on a worker thread. When your method is finished, the event will be called again if there was new data received while handling the event. That means, it triggers when data is received, not when data is in the buffer (small subtle difference).

i.e. if DataReceived is triggered and there are two bytes in the buffer, reading a single byte will still leave one byte in the buffer. You'll only get notified when again there's a new byte received, making 2 or more bytes in the buffer.

So you should do something like this in your DataReceived event:
int r;
do {
  r = Read(...);
  if (r > 0) {
    // Process
} while (r > 0);
That will empty the buffer during the event. With that code, you may get a pending event so that doing a Read() may return zero bytes. Just ignore it in this case.