0

I have multithread readers/writers that use shared collection.

foreach (var account in accounts)
{
  ThreadPool.QueueUserWorkItem(o => Execute(account));
}

in Execute Method I read static Dictionary, get first record where value is null and block it.

do
{
  if (collection.Any(x => x.Value == null))
      {
          var wall = collection.First(x => x.Value == null).Key;
          collection[wall] = 0; //block
          //Do something
          Console.Write(wall);
          collection[wall] = result;
      } 
} while (collection.Any(x => x.Value == null));

In result in console I get all walls that thread visited:

thread 1 : ABDFH

thread 2 : ACEFG

I read this post, but BlockingCollection using to block unsafety add or delete element, how to thread-safety change collection? I use .NET 4.0.

Community
  • 1
  • 1
Dr_klo
  • 469
  • 6
  • 19
  • The Dictionary you use is not thread-safe without the *lock* keyword. If you want to use a BlockingCollection then consider putting the "walls" into it so the consumers each obtain a unique wall to work on. – Hans Passant Dec 04 '15 at 12:08
  • You are overwriting the results as some of your threads in the same moment of time got exactly one `wall` number. You must sync your threads or refactor your logic. – VMAtm Dec 04 '15 at 13:26

0 Answers0