Thursday, November 12, 2009

New coordination datastructures in .Net 4.0 Beta 2

To be honest a have not spent too much time looking at .Net 4.0 beta 2 yet. But I do keep up with the blogs concerning Parallel Extensions. Josh Philps has just posted an entry about the changes that were made in the Coordination Data Structures (CDS) in Beta 2. The CDS are the types that have been added to the framework that will help writing concurrent applications without having to do (to much of) your own synchronization. I used two of the CDS classes (ConcurrentDictionary<Tkey, TValue> and Lazy<T>) in the CacheDictionary that I wrote about in this article.

   1: public class CacheDictionary<TKey, TValue>   
   2:     where TValue : class // needs to be a ref type due to current limitation of lazyInit<>   
   3: {   
   4:     ConcurrentDictionary<TKey, LazyInit<TValue>> _cacheItemDictionary = new ConcurrentDictionary<TKey, LazyInit<TValue>>();   
   5:   
   6:     public TValue Fetch(TKey key, Func producer)   
   7:     {   
   8:         LazyInit cacheItem;   
   9:         if (!_cacheItemDictionary.TryGetValue(key, out cacheItem))   
  10:         {   
  11:             cacheItem = new LazyInit(() => producer(), LazyInitMode.EnsureSingleExecution);   
  12:   
  13:             if (!_cacheItemDictionary.TryAdd(key, cacheItem))   
  14:             {   
  15:                 // while we never remove items, if TryAdd fails it should be present   
  16:                 cacheItem = _cacheItemDictionary[key];   
  17:             }   
  18:         }   
  19:         return cacheItem.Value;   
  20:     }   
  21: }