使用HttpRuntime.Cache的问题 [英] Issue using HttpRuntime.Cache

查看:105
本文介绍了使用HttpRuntime.Cache的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Am使用以下.net代码将对象添加到缓存:

Am using following .net code to add objects to cache:

public static void Add<T>(string key, T dataToCache)
{
    try
    {
        ApplicationLog.Instance.WriteInfoFormat("Inserting item with key {0} into Cache...", key);

        HttpRuntime.Cache.Insert(
            key,
            dataToCache,
            null,
            DateTime.Now.AddDays(7),
            System.Web.Caching.Cache.NoSlidingExpiration);
    }

    catch (Exception ex)
    {
        ApplicationLog.Instance.WriteException(ex);             
    }
}

这是我的代码,用于从缓存中检索值:

and here is my code to retrieve values from cache:

public static T Get<T>(string key) 
{   
    try
    {                
        if (Exists(key))
        {
            ApplicationLog.Instance.WriteInfoFormat("Retrieving item with key {0} from Cache...", key);

            return (T)HttpRuntime.Cache[key];
        }
        else
        {
            ApplicationLog.Instance.WriteInfoFormat("Item with key {0} does not exist in Cache.", key);
            return default(T); 
        }
    }
    catch(Exception ex)
    {
        ApplicationLog.Instance.WriteException(ex);
        return default(T); 
    }
}


public static bool Exists(string key)
{
    bool retVal = false;
    try
    {
        retVal= HttpRuntime.Cache[key] != null;
    }
    catch (Exception ex)
    {
        ApplicationLog.Instance.WriteException(ex);
    }
    return retVal; 
}

但是我发现每隔2分钟左右,缓存的对象值为设置为null会导致再次从数据库中提取该值。

But i find that after every 2 minutes or so,the cached object value is getting set to null resulting in pulling that value from database again.

我在这里缺少什么?

推荐答案

当您说每两分钟插入的值设置为null时,是否仅表示您感兴趣的项目或缓存中的每个项目?

When you say every two minutes the value inserted is set to null, does that mean just the item you're interested in or every single item in the cache?

我之所以这样问,是因为仅在应用程序运行时才存在缓存。如果重新启动应用程序,则缓存将消失。如果一切每2分钟消失一次,这将解释该行为。在这种情况下,您会遇到另一个问题:为什么应用程序每2分钟重新启动一次。

I ask this because the cache only exists as long as the application is running. If the application is restarted, the cache goes away. This would explain the behavior if everything goes away every 2 minutes. In that case you have a different problem on your hands: why does the application restart every 2 minutes.

如果只是某些项目,则可能是内存问题。高速缓存会清理自身以响应内存不足的情况。我相信有一种方法可以为插入的值设置优先级。但这仅在内存不足时才是一个问题。

If it's only SOME items then it could be a memory issue. The cache cleans itself up in response to low memory. I believe there's a way to set priority on values inserted. But this should only be a problem when you're low on memory.

如果这仍然不能解决您的问题,则有一种方法可以找出为什么一个项目是被删除。在此处解释。

If this still doesn't solve your problem, there is a way to discover why an item is being removed. It is explained here.

这篇关于使用HttpRuntime.Cache的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆