使用ConcurrentBag <T>作为ConcurrentDictionary <key,object>的对象是否正确

Pau*_*era 8 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];
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

编辑添加:只有1个线程将添加到包/列表,另一个线程将删除,但许多线程可以访问.

yam*_*men 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];
    }
}
Run Code Online (Sandbox Code Playgroud)

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