1

我打电话var person = PersonDB.pDict["395096"];

谁能解释一下为什么这段代码会阻塞:

static class PersonDB
{
    internal static readonly ConcurrentDictionary<string, Person> pDict;

    static PersonDB()
    {
        pDict = new ConcurrentDictionary<string, Person>();
        var headers = File.ReadLines(FindPath.DataSetPerson).First().Split(';');


        File.ReadLines(FindPath.DataSetPerson).AsParallel().Skip(1).Select(s => s.Split(';')).ForAll(fa =>
           pDict.TryAdd(fa[0], new Person() { all = Enumerable.Range(0, fa.Length).ToDictionary(t => headers[t], d => fa[d]) })
        );
    }
}

sealed class Person
{
    public Dictionary<string, string> all;
}

虽然这部分不会阻塞:

static class PersonDB
{
    internal static readonly ConcurrentDictionary<string, Person> pDict;

    static PersonDB()
    {
        pDict = new ConcurrentDictionary<string, Person>();
        var headers = File.ReadLines(FindPath.DataSetPerson).First().Split(';');


        //File.ReadLines(FindPath.DataSetPerson).AsParallel().Skip(1).Select(s => s.Split(';')).ForAll(fa =>
        //   pDict.TryAdd(fa[0], new Person() { all = Enumerable.Range(0, fa.Length).ToDictionary(t => headers[t], d => fa[d]) })
        //);

        Parallel.ForEach(File.ReadLines(FindPath.DataSetPerson).Skip(1).Select(s => s.Split(';')), line =>
        {
            pDict.TryAdd(line[0], new Person() { all = Enumerable.Range(0, line.Length).ToDictionary(t => headers[t], d => line[d]) });
        });

    }
}

sealed class Person
{
    public Dictionary<string, string> all;
}

老实说,我什至不确定后者现在是否是线程安全的,但至少它运行没有问题。我想知道如何使 PersonDB 成为线程安全类,这样就不会出现竞争条件或死锁。pDict 需要在使用 pDict 时创建一次。我认为静态构造函数是一个很好的解决方案,但是 PLINQ 查询的执行停止让我非常不确定......

4

1 回答 1

3

这是一个静态构造函数死锁。PersonDB阻塞直到PersonDB被静态初始化的并行线程访问。将初始化代码移动到不同的函数。使其返回字典而不是pDict就地修改。

我尽量避免使用可能会失败的静态构造函数。您的代码肯定会失败,因为它是 IO。如果确实如此,则该课程将被永久冲洗。Lazy可以更好。

于 2015-08-05T14:55:28.483 回答