Following problem:
In a class I have a loop in which data, polled from a serial port, are written to a circular buffer (Byte Array), in the same loop I want to send sentences (from ReadPtr to the next LF-Byte) with an event handler to the main program. What is the best way (parameter type of the eventhandler) to do this as fast as possible and without creating much work for the carbage collector.
The originally used approach was to copy the data to a string:
string response = ;
for (i = 0; i < bytesToSend; i++)
{
response = response + (char)RingBuffer[ReadPtr + i];
}
OnDataReceived(this, response); // Call of eventhandler
The disadvantages of this approach is, as I think, that copying to the string is time consuming and that lots of string instances are created.
I tried another approach, namely to pass the RingBuffer, the startindex and the ByteCount as parameters of the eventargs with the eventhandler. This should be fast, as the RingBuffer is transferred as a reference type and no new objects are created (for GC). The disadvantage is that if the data are not read at once by the event listener, they can be overwritten with new data in the RingBuffer. A means to prevent this could be an autoResetEvent in the loop which is set when the eventhandler has read the data and is terminating. (This should slow down the application ?).
Another approach would be to create a new byte Array for each data sentence, copy the data in this Byte Array and use this new Byte Array as event argument. The disadvantage would be more work for GC.
Does anybody have an idea for better solutions or ideas how the disadvantage of the different approaches could be avoided?