开发者

shared asp.net object as static or cache

What is the best method of storing a shared object in asp.net? It will get called multiple times per request o开发者_StackOverflown every request. Ive been using these two methods but Id like to know if there is a better way. I refresh this object once an hour.

public static List<ResourceObject> SharedResources = new List<ResourceObject>()

//OR

public static List<ResourceObject> SharedResources
{
    get
    {
        List<ResourceObject> _sharedResources = HttpContext.Current.Cache["RedirectRoutes"] as List<ResourceObject>;
        if (_sharedResources == null)
        {
            _sharedResources = LoadNewSharedResource();
            HttpContext.Current.Cache["RedirectRoutes"] = _sharedResources;
        }

        return _redirectRoutes;
    }
    set
    {
        HttpContext.Current.Cache["RedirectRoutes"] = value;
    }
}


If your object is changing frequently (i.e. hourly as you mentioned) then you'll be best to use the cache as it will be able to take care of flushing for you (assuming you pass the correct parameters when adding the value to the cache). If you use a static value it will not be cleared out every hour automatically so you'd need to implement the check yourself.


If this is, as it seems, an object that needs to persist across requests, then this is a perfectly good and reasonable way to achieve it. You may want to put the cached version in a local variable if it is being accessed multiple times within one call, to save retrieving it from the cache each time.

Is there a specific issue with caching it like that that you are concerned about?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜