Accessing dictionaries in a multithreaded environment.

Accessing dictionaries in a multithreaded environment.

Old forum URL: forums.lhotka.net/forums/t/7945.aspx


markell posted on Wednesday, November 04, 2009

Hi,
I have stumbled upon this code while debugging deep in CSLA:
      if (!(cache.TryGetValue(objectType, out list)))
      {
        lock (cache)
        {
          if (!(cache.TryGetValue(objectType, out list)))
          {
My question is it safe to use the if-lock-if pattern with ordinary dictionaries? Because, I have the same problem and seeking for an advice on StackOverflow yielded this short discussion - http://stackoverflow.com/questions/1593628/accessing-net-dictionary-in-a-multithreaded-environment.
The folks there are very determined against this approach, which makes me really sad. And here, in CSLA, I see it in use. So, my question is this safe or not?
Thanks.

RockfordLhotka replied on Wednesday, November 04, 2009

I suppose the risk here is that TryGetValue() could return true, but 'list' could be returned as null.

It is a tough issue though, because the clear alternative is to always lock everything, causing broad cross-locking issues, especially on web or app servers.

.NET 4.0 is introducing some richer collection types that offer good synchronization behaviors (finally), including ConcurrentDictionary, so hopefully many of these things will become non-issues at that point.

markell replied on Thursday, November 05, 2009

Thanks to all of you. Of course, I prefer if-lock-if approach. I have to check when .NET 4.0 is out.
Thanks again.

rasupit replied on Wednesday, November 04, 2009

I guess if you're willing to sacrifice performance and scalability to get the most thread-safe, i'd echo Rocky that you should fully lock everything including read.

You may consider using ReaderWriterSlim instead of locking the dictionary or use sync lock.  Other option is to take a look at how asp.net team implement RouteCollection.  You can read more info about it here.

Ricky

Copyright (c) Marimer LLC