YouMiss

Currently, I am developing an application which receives operating instructions from a large-frame PLC, processes them and update the database accordingly.

Base on our previous system, it's predictable that the database processing speed is slower than the receiving speed of PLC instructions. So, I decided to wrap the raw incoming PLC instructions with a class object and queue them into a buffer before sent to the database processing unit.

My initial thought was that using a generic Queue type to enqueue each wrapped PLC instrution object and dequeue them by a forever loop at the other end of the queue. Since, I am new to programming, so I have concerns with the thread safty in this scenario; also I am not intended to use a forever loop in a worker thread.

However, I haven't figured out a proper way to complete this. I wonder that anyone of you could kindly explain to me the possibility of this simple buffer implementation or recommend me another method to do it.

Thanks to you in advance.



Re: Visual C# General A question about implementing an object buffer.

OmegaMan

The generic queue is an excellent usage for this scenario and having one thread populate it and another thread extract are perfectly fine. What you need to do to make it thread safe is to wrap any call to it by a lock such as

lock(myQueue)
{
myQueue.Enque(myValue);
}

Here is such a block to safely check for messages if one exists:

Queue<string> messages = new Queue<string>();
 
string action = string.Empty;
 
lock (messages)
{
  if (messages.Count > 0)
    action = messages.Dequeue();
 
}
 
// Now check to see if we have a valid message to process
if (string.IsNullOrEmpty(action) == false)
{
// Do work
}







Re: Visual C# General A question about implementing an object buffer.

YouMiss

Your answer is of great help. I did consider using a lock block to synchronize the "Enqueue()" and "Dequeue()" process, but I didn't realize that I could use it in this way.





Re: Visual C# General A question about implementing an object buffer.

OmegaMan

As I like to say, the Tribal Knowledge concerning generic collections is that most of them are not thread safe. Even though it looks hooky, one still needs to protect calls to count/length and thier similar counterparts to be on the safe side. See System.Collections.Generic Namespace for more info.