The behavior is undefined. When we develop a class that is not thread-safe, it 
means that we don't even test to see if what happens if multiple threads party 
on it at the same time. When you do that all bets are off.

From: ozdotnet-boun...@ozdotnet.com [mailto:ozdotnet-boun...@ozdotnet.com] On 
Behalf Of Wallace Turner
Sent: Thursday, June 03, 2010 4:39 AM
To: 'ozDotNet'
Subject: Dictionary thread-safe-ness

Hi,

In short, could you encounter a deadlock whilst accessing a Dictionary object 
in a thread-unsafe manner ?

Consider a class containing a Dictionary and a method to add to the Dictionary. 
Assume 2 threads call Add( )


public class SomeClass
            {
                  private Dictionary<int, List<ClassA>> _dictionary = new 
Dictionary<int, List<ClassA>>();

                  private void Add(int id, ClassA someObj)
                  {
                        List<ClassA> list = null;
                        if (!_dictionary.TryGetValue(id, out list))//thread1 
hung here
                        {
                              list = new List<ClassA>();
                              list.Add(someObj);//thread2 hung here
                              _dictionary.Add(id, list);
                        }
                        else
                        {
                              list.Add(someObj);
                        }
                  }
            }

I encountered a deadlock recently. When I paused the debugger the threads were 
hung at the indicated position. That is, one was trying to Get and the other 
trying to Add.

The docs regarding Dictionary and Thread Safety state:
A Dictionary<TKey, TValue> can support multiple readers concurrently, as long 
as the collection is not modified. Even so, enumerating through a collection is 
intrinsically not a thread-safe procedure. In the rare case where an 
enumeration contends with write accesses, the collection must be locked during 
the entire enumeration. To allow the collection to be accessed by multiple 
threads for reading and writing, you must implement your own synchronization.
It says 'must be locked' without explaining the consequences. I am aware of the 
non-deadlocking consequences but I didn't expect it to deadlock! (perhaps it 
did not and it was something else, I had lots of threads and did not 
investigate this at the time)

Regards

Wal

Reply via email to