I am working on an application that will connect to x number of hardware devices. I have designed the ReaderLayer such that there is a dedicated thread where the code runs to connect to a single device and continuously read the device data buffer. The code for the reader layer is as follows:
while (true)
{
// read buffer from the reader
IList<IRampActiveTag> rampTagList = ConnectedReader.ReadBuffer();
if (rampTagList != null && rampTagList.Any())
{
// trigger read event handler
if (ReadMessage != null)
ReadMessage(this, new RampTagReadEventArg(rampTagList));
}
}
There is a Logic Layer built on top of the Reader Layer that is responsible for processing the data received from the Readers and forwarding it via HTTP Post. It has y number of threads each running a separate Logic Block that has to process relevant information that gets written to its thread-safe queue. The logic layer subscribes to the ReadForward
event that is exposed by the Reader Layer and forwards that data to the relevant logic block by writing to its ConcurrentQueue
.
The code in each of the Logic Block is pretty straightforward:
public void ProcessLogicBuffer()
{
while (true)
{
// Dequeue the list
IRampActiveTag tag;
LogicBuffer.TryDequeue(out tag);
if (tag != null)
{
ProcessNewTagReceivedLogic(tag);
Console.WriteLine("Process Buffer #Tag {0}. Buffer Count #{1}", tag.NewLoopId, LogicBuffer.Count);
}
}
}
The layout of the loop is mostly the same for both the Reader Layer and the Logic Layer while(true)
. However when I tested with 3 readers and 3 logic blocks, I found that my CPU utilization jumped up to 77%. I quickly narrowed down the CPU usage to Logic Threads as I received 50% usage for 2 and 25% usage for 1 block.
I am able to bring down the CPU usage to ~3% simply by adding in a Thread.Sleep(100) in the logic thread with 3 blocks, however, I am worried that my logic could be out of synch. By looking at the sample could anyone please suggest to me any improvements as the production code will need to work with about 30 logic blocks. Do I need to change my architecture?