1

In my ASP.NET Web application, all the requests to pages access this common static cache class. (So it has to be thread safe)

Is it safe to refresh this cache by calling the Refresh method of Cache class as implemented below. Or it causes sync problems?

    static class Cache
    {
        static Dictionary<string, string> cachedCodeNames;
        static readonly object sync = new object();

        public static string GetName(string code)
        {
            return CodeNames[code];
        }

        public static void Refresh()
        {
            cachedCodeNames = null;
        }

        static Dictionary<string, string> CodeNames
        {
            get
            {
                if (cachedCodeNames == null)
                {
                    lock (sync)
                    {
                        if (cachedCodeNames == null)
                        {
                            cachedCodeNames = WebServiceManager.GetCodeNameCache();
                        }
                    }
                }
                return cachedCodeNames;
            }
        }
    }

    static class WebServiceManager
    {
        internal static Dictionary<string, string> GetCodeNameCache()
        {
            throw new NotImplementedException();
        }
    }
Ahmet Altun
  • 3,910
  • 9
  • 39
  • 64

1 Answers1

0

There's certainly a race condition here. If one thread has just stepped out of the lock and at that point another thread calls (and completes) Refresh, the first thread is going to return null from CodeNames. If CodeNames was being read from inside GetName, this will immediately result in a NullReferenceException.

To prevent this, you 'd need to either protect Refresh with a lock(sync) or rewrite CodeNames like this:

lock (sync)
{
    if (cachedCodeNames == null)
    {
        var codeNames = WebServiceManager.GetCodeNameCache();
        cachedCodeNames = codeNames;
        return codeNames;
    }
}

Of course in this case you should apply generous amounts of comments to make clear that this seemingly pointless ritual is in fact an important feature.

Jon
  • 428,835
  • 81
  • 738
  • 806