Mulithreading Issues

Feb 27, 2009 at 2:34 PM
Hi there.

I have been using this library for a few weeks now, and I am very happy with it.  However, I would like to share you with you some issues I have come across.  I found that your library does not work in a multithreaded environment. The issue lies in in the FashReflectionCache class and use of the Dictionary for caching.  Even though you are locking on the key, I found that race conditions can still occur resulting in null reference exceptions arising internally from the Dictionary class itself.  However, I have manged to resolve this, by making use of a thead safe dictionary instead of the standard MS Dictionary class.

I used the a ThreadSafeDictionary class developed by Brian Rudulph ( and since using this class instead, I have not run into any issues.

Using the ThreadSafeDictionary allows you do do away with your locking mechanism, and is more performant as it makes use of a reader/writer lock,  The code now looks this this.

private readonly ThreadSafeDictionary<TKey, TValue> _cache = new ThreadSafeDictionary<TKey, TValue>();

/// <summary>
/// Gets the a value from the cache using the specifed key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public TValue Get(TKey key)
    TValue value = default(TValue);
    if (_cache.TryGetValue(key, out value))
        return value;

    //retest as may have been hit by another thread
    if (!_cache.TryGetValue(key, out value))
        value = Create(key);
        _cache[key] = value;
    return value;

If you need any further info from me, I would be pleased to oblige.

Steve Solomon