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
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.