Alex Rivera | Logout

ContainsKey Thread Safe

Asked 2009-04-02T17:14:36.603
11

In the following code:

public class StringCache
{
    private readonly object lockobj = new object();

    private readonly Dictionary<int, string> cache = new Dictionary<int, string>();

    public string GetMemberInfo(int key)
    {
        if (cache.ContainsKey(key))
            return cache[key];
        lock (lockobj)
        {
            if (!cache.ContainsKey(key))
                cache[key] = GetString(key);
        }
        return cache[key];
    }

    private static string GetString(int key)
    {
        return "Not Important";
    }
}

1) Is ContainsKey thread safe? IOW, what happens if that method is executing when another thread is adding something to the dictionary? 2) For the first return cache[key], is there any chance that it could return a garbled value?

TIA,

MB

Edit
Report

1 Answer

1

Dictionary is not Thread-Safe.

If you say that

what happens if that method is executing when another thread is adding something to the dictionary?

then I suppose other functions access the cache as well. You need to synchronize accesses(reading and writing) to the cache. Use your lock object in all of these operations.

answered 2009-04-02T17:38:37.513

Your Answer