getting argument exception in concurrent dictionary when sorting and displaying as it is being updated

后端 未结 2 523
既然无缘
既然无缘 2021-01-13 00:44

I am getting a hard to reproduce error in the following program in which a number of threads update a concurrent dictionary in parallel and the main thread displays the stat

2条回答
  •  我在风中等你
    2021-01-13 00:58

    After a discussion with ChrisShain in the comments, the conclusion is that you should get mutually exclusive access to the dictionary before printing it out, either with a mutex of a lock statement.

    Doing it with a lock:

    public void WriteBatch(IEnumerable> batch)
    {
        lock (myLock) 
        {
            foreach (var tuple in batch)
            {
                Console.WriteLine("{0} - {1}", tuple.Item1, tuple.Item2);
            }
            Console.WriteLine();
        }
    }
    

    assuming you allocated a myLock object at the class level. See example.

    Doing it with a mutex:

    public void WriteBatch(IEnumerable> batch)
    {
        mut.WaitOne();
    
        foreach (var tuple in batch)
        {
            Console.WriteLine("{0} - {1}", tuple.Item1, tuple.Item2);
        }
        Console.WriteLine();
    
        mut.ReleaseMutex();
    }
    

    Again, assuming you allocated a Mutex object at the class level. See example.

提交回复
热议问题