my C # application reads data from a special USB device. Data is read as so-called โmessagesโ, each of which has 24 bytes. The number of messages to be read per second may vary (the maximum frequency is quite high, about 700 messages per second), but the application must read them.
The only way to read messages is to call the ReadMessage function, which returns a single message read from the device. The function is from an external DLL, and I cannot change it.
My solution: I have a separate thread that runs all the time during the start of the program, and the only task is to read messages in a loop. Received messages are then processed in the main thread of the application.
The function executed in the "read stream" is as follows:
private void ReadingThreadFunction() {
int cycleCount;
try {
while (this.keepReceivingMessages) {
cycleCount++;
TRxMsg receivedMessage;
ReadMessage(devHandle, out receivedMessage);
}
}
catch {
}
}
This solution works fine, and all messages are received correctly. However, the application consumes too many resources, the processor of my computer is running at more than 80%. Therefore, I would like to reduce it.
Thanks to the "cycleCount" variable, I know that the "speed" of the flow is about 40,000 cycles per second. This is too much, since I need to receive a maximum of 700 messages / sec. (and the device has a buffer for about 100 messages, so the cycle speed may even be slightly lower)
, 1 Thread.Sleep(1); . , , 70 , . , , , , 1 .
, : ( ), Thread.Sleep? - Thread, Threading.Timer ThreadPool?
. , , , , , .