Drastically reduce CPU usage and allocations #2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
SerialPort.Read
takes acount
parameter, which specifies the maximumnumber of bytes to read from the serial port. If this is non-zero, then
the
Read
call will block until at least 1 byte has been received.Previously, if there were no bytes available to read, then the code span
in a polling loop until a byte became available, burning CPU. It's more
efficient to call
Read
with a non-zerocount
parameter in this case,which causes the thread to sleep until one or more bytes are available.
Change the
Run
method to follow the normal pattern of allocating a singlebuffer, and then reading some number of bytes into it, and processing
just the bytes which were read. This also avoids the thousands of
allocations of single-byte arrays which were happening previously.
The
_sleepTime
field is now a bit redundent: I assume this was addedin an attempt to reduce CPU usage. I've left it in out of backwards
compatibility concerns, but it's not adding anything useful any more.