将ConcurrentBag <t>用作ConcurrentDictionary的对象<key,object =“”> </key,> </t>是否正确

时间:2012-05-01 20:16:58

标签: c# multithreading

在以下代码中:

public class SomeItem { }
public class SomeItemsBag : ConcurrentBag< SomeItem > { }
public class SomeItemsList : List< SomeItem > { }
public static class Program
{
    private static ConcurrentDictionary< string, SomeItemsBag > _SomeItemsBag;
    private static ConcurrentDictionary< string, SomeItemsList > _SomeItemsList;

    private static void GetItem(string key)
    {
        var bag = _SomeItemsBag[key];
        var list= _SomeItemsList[key];
        ...
    }
}

我的假设是包是线程安全的而列表不是。这是处理多线程应用程序中的列表字典的正确方法吗?

编辑添加: 只有1个线程会添加到包/列表中,另一个线程会被删除,但很多线程都可以访问。

1 个答案:

答案 0 :(得分:2)

您认为ConcurrentBag是线程安全且List不正确的假设。但是,您可以同步对列表的访问,例如:

private static ConcurrentDictionary< string, SomeItemsBag > _SomeItemsBag;
private static ConcurrentDictionary< string, SomeItemsList > _SomeItemsList;
private static object _someItemsListLocker = new object();

private static void GetItem(string key)
{
    var bag = _SomeItemsBag[key];
    lock (_someItemsListLocker) {
        var list = _SomeItemsList[key];
    }
}

但是,如果您想要了解应该使用哪种数据结构的更全面的建议,最好完全描述一下情况。请注意,还有ConcurrentQueueConcurrentStack可能会更好地满足您对列表的要求。它们在多线程场景中进行了优化,因为添加和删除只能分别在一侧进行(堆栈的相同侧,队列的相对侧)。