8

在以下代码中:

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];
        ...
    }
}

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

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

4

1 回答 1

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];
    }
}

However, you're better off describing the situation completely if you want more holistic advice as to what data structure you should be using. Note that there are also ConcurrentQueue and ConcurrentStack which may be better for what you want over the list. They are optimised in multi-threaded scenarios since addition and removal can only happen on one side respectively (same sides for stack, opposite sides for queue).

于 2012-05-01T21:13:30.227 回答