The below code handles a socket message coming in with a 2 parameters. It puts information into a queue and is processed on another thread. My question is if 2 messages come in right after the other and are then dequeued and sent to the method ProcessData, is there a race condition on ProcessData?
private void DataIn(long Code, string Message)
{
if (!Started)
{
if (DataInQueue == null)
DataInQueue = new Queue();
DataInThread = new Thread(new ThreadStart(ThreadProcedure));
DataInThreadEnding = false;
DataInThread.IsBackground = true;
DataInThread.Start();
Started = true;
}
DataInQueue.Enqueue(new cDataIn(Code, Message));
}
private void ThreadProcedure()
{
while (!ProgramEnding)
{
Queue mySyncdQ = Queue.Synchronized(DataInQueue);
if (mySyncdQ != null && mySyncdQ.Count > 0)
{
cDataIn data = null;
// Creates a synchronized wrapper around the Queue.
if (mySyncdQ.Count > 0)
data = (cDataIn)mySyncdQ.Dequeue();
ProcessData(data);
}
}
}
UPDATE
Queue is not used in a thread-safe manner in your code… the code you show is not enough to be sure whether there is a race condition but with the
ConcurrentQueueyou get a better performance… and in the ThreadProcedure you can have calling ProcessData with null and as far as I can tell to be on the safe side ProcessData should be reentrant for all this to work…Use a
ConcurrentQueue– that avoids some possible problems… and check outBlockingCollectionwhich is designed for thread-safe Producer/Consumer scenarios… both work mostly lock-free and are really fast…