开发者

Caching global data in an iis website

I have READONLY object graph that is cached for one minute so that it can be used by all threads (Code below).

public class ObjectGraphCache
{
    static readonly Object storeLock = new object();

    public ObjectGraph AllForElection(int ElectionId, System.Web.Caching.Cache cache)
    {
        string key=string.Format("AllForElection{0}",
            ElectionId);
        int timout = int.Parse(ConfigurationManager.AppSettings["dbCacheTimeInSeconds"]);

        if (timout == 0)
        {
            ObjectGraph graph = new ObjectGraph();
            graph.AllForElection(ElectionId);
            return graph;
        }
        else
        {
            Object obj = cache[key];
            if (obj == null)
            {
                lock (storeLock)
                {
                    obj = cache[key]; // In case another page got the lock first and your are queued (Ensures on开发者_如何学编程ly one get per cycle)
                    if (obj == null)
                    {
                        // Not in cache
                        ObjectGraph graph = new ObjectGraph();
                        graph.AllForElection(ElectionId);

                        cache.Insert(
                            key,
                            graph,
                            null,
                            DateTime.Now.Add(new TimeSpan(0, 0, timout)),
                            System.Web.Caching.Cache.NoSlidingExpiration);
                        return graph;
                    }
                }
            }
            return (ObjectGraph)obj;
        }

However I want to know : Why use the Cache object, when I more easily store the READONLY object as a static. This stores a pointer to the heap, so when it is updated, threads still processing the previous pointers object will carry one fine with the old object, AND also I would not have to cast the object from the cache before returning it. Anyone see any gotchas?


put storeLockin an application variable

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜