在尝试创建并发 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
)
最佳答案
ConcurrentQueue
本身没问题,只要您不改变存储为它的元素的数组。
但是,您的使用模式 ManualResetEvent
建议有更好的解决方案:如果您使用 BlockingCollection<T>
,您将能够避免进行手动同步。
关于c# - 正确使用 .NET 并发集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13332666/