简体   繁体   English

共享 asp.net object 为 static 或缓存

[英]shared asp.net object as static or cache

What is the best method of storing a shared object in asp.net?在 asp.net 中存储共享 object 的最佳方法是什么? It will get called multiple times per request on 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.我每小时刷新一次这个 object。

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 (ie 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).如果您的 object 经常更改(即您提到的每小时一次),那么您最好使用缓存,因为它将能够为您处理刷新(假设您在将值添加到缓存时传递了正确的参数) . If you use a static value it will not be cleared out every hour automatically so you'd need to implement the check yourself.如果您使用 static 值,则不会每小时自动清除一次,因此您需要自己实施检查。

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.如果这看起来是一个需要跨请求持续存在的 object,那么这是实现它的完美且合理的方法。 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?像您关心的那样缓存它是否存在特定问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM