In my attempt to create concurrent Socket operations, I’ve created the following code:
ConcurrentQueue<byte[]> messageQueue;
ManualResetEvent resetEvent;
Thread outThread; // -> new Thread(BeginSending);
public void BeginSending() // invoked by outThread
{
while (true)
{
resetEvent.WaitOne();
while (messageQueue.Count > 0)
{
byte[] msg;
messageQueue.TryDequeue(out msg);
// send msg via socket
}
resetEvent.Reset();
}
}
public void QueueMessage(byte[] msg) // invoked by the main thread
{
messageQueue.Enqueue(msg);
resetEvent.Set();
}
Is adding items to the ConcurrentQueue while a different thread is iterating/dequeuing it a dangerous thing?
From my understanding many synchronized collections simply have individually synchronized methods, but is the same true for concurrentQueue and similar collections?
(ConcurrentBag, ConcurrentDictionary, ConcurrentStack)
The
ConcurrentQueueitself is OK, as long as you are not mutating the arrays stored as its elements.However, your usage pattern with
ManualResetEventsuggests that there is a better solution: if you useBlockingCollection<T>, you would be able to avoid doing manual synchronization.