在我尝试创建并发Socket
操作时,我创建了以下代码:
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();
}
在不同的线程迭代/出队时添加项目ConcurrentQueue
是一件危险的事情吗?
据我了解,许多同步集合只是具有单独的同步方法,但对于concurrentQueue
类似的集合来说也是如此吗?
( ConcurrentBag
, ConcurrentDictionary
, ConcurrentStack
)