开发者

Are ASP.NET Cache values scoped equally or more narrowly than a static variable?

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 scop开发者_开发知识库e (or narrower scope) than static variables.

Does anyone know of documentation to this effect?


// 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜