views:

34

answers:

2

In order to synchronise access to a Dictionary object in the ASP.NET cache, it is recommended that a synchroniser object be used.

Dino Esposito recommends a static variable as the target for locking (See http://www.drdobbs.com/cpp/184406369). However, this will only work if the ASP.NET Cache values have the same scope (or narrower scope) than static variables.

Does anyone know of documentation to this effect?

+1  A: 

// Update based on comment The cache is unique per app domain, so you don't need to worry. See MSDN here

There is one instance of the Cache class per application domain. As a result, the Cache object that is returned by the Cache property is the Cache object for all requests in the application domain.

// Original answer

I'm not sure I quite understand your question. Anything in the cache is globally accessible (or at least accessible by anything that has access to the cache object).

This code would be safe as long as it is the only place you access the object.

    private static readonly object lockme = new object();
    public void SetDictionaryValue(string key, string value)
    {
        lock (lockme)
        {
            var lookup = (Dictionary<string, string>)GetFromCache("LookupDictionary");
            lookup["key"] = value;
        }
    }

    public string GetDictionaryValue(string key)
    {
        lock (lockme)
        {
            var lookup = (Dictionary<string, string>)GetFromCache("LookupDictionary");
            return lookup["key"];
        }
    }

But yes, it's not guaranteed to be safe as there could be other code that retrieves the dictionary from the cache somewhere else and modifies it. Not sure how you could guarantee that that couldn't happen. I mean you could use a GUID as a key, but you can iterate over all the cache variables anyway.

I'm not sure if I'm helping you here?

Andrew Barrett
I guess my question could be rephrased "Are values in the ASP.NET Cache object available outside the AppDomain which submitted the values". If so, a static variable lock will not do.
goofballLogic
The cache lives inside the current AppDomain, I'll try find some official documentation to that effect and update my answer.
Andrew Barrett
A: 

Why don't you lock on the dictionary objects? Then your lock would be even more fine-grained. Although I agree with Andrew that a lock on a static object is fine.

chris166