c# - 正确使用 .NET 并发集合

标签 c# .net multithreading .net-4.0 concurrency

在尝试创建并发 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, ConcurrentDictionaryConcurrentStack)

最佳答案

ConcurrentQueue本身没问题,只要您不改变存储为它的元素的数组。

但是,您的使用模式 ManualResetEvent建议有更好的解决方案:如果您使用 BlockingCollection<T> ,您将能够避免进行手动同步。

关于c# - 正确使用 .NET 并发集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13332666/

相关文章:

android - 如何不在主线程上运行服务?

c# - Xamarin HTTPClient : Error when accessing specific web service

c# - C#、F#、IronPython 和 IronRuby 的集成

c# - Linq Union,避免空数据和重复数据

c# - 使用变量更改图片框中的图片

c# - ViewState 仅在 Safari 中无效

java - Servlet 似乎没有以线程方式执行

java多线程未利用所有核心

C# SOAP 调用不断返回 500 错误

c# - 将复选框可见性绑定(bind)到转换后的 bool 值和另一个复选框可见性