C# - 从缓存中插入和删除

Nir*_*Nir 16 c# asp.net caching

  1. 如果我通过赋值来插入Cache:

    Cache ["key"] = value;

    什么是到期时间?

  2. 从缓存中删除相同的值:

    我想检查值是否在Cache by中if(Cache["key"]!=null),是否最好将其从Cache中移除Cache.Remove("key")Cache["key"]=null

- 编辑 -

之后尝试过Cache.RemoveCache["key"]=null,请不要使用Cache["key"]=null,因为在紧张时会抛出异常.

bni*_*dyc 11

1 Cache["key"] = value等于Cache.Insert("key", value)

MSDN Cache.Insert - 方法(String,Object):

此方法将覆盖其键与key参数匹配的现有缓存项.使用Insert方法的重载添加到缓存中的对象插入时没有文件或缓存依赖项,优先级为Default,NoSlidingExpiration的滑动到期值以及NoAbsoluteExpiration的绝对到期值.

2最好通过Cache.Remove("key")从缓存中删除值.如果你使用Cache["key"] = null它等于Cache.Insert("key", null).看一下Cache.Insert实现:

public void Insert(string key, object value)
{
    this._cacheInternal.DoInsert(true, key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true);
}
Run Code Online (Sandbox Code Playgroud)

并且CacheInternal.DoInsert:

internal object DoInsert(bool isPublic, string key, object value, CacheDependency dependencies, DateTime utcAbsoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback, bool replace)
{
    using (dependencies)
    {
        object obj2;
        CacheEntry cacheKey = new CacheEntry(key, value, dependencies, onRemoveCallback, utcAbsoluteExpiration, slidingExpiration, priority, isPublic);
        cacheKey = this.UpdateCache(cacheKey, cacheKey, replace, CacheItemRemovedReason.Removed, out obj2);
        if (cacheKey != null)
        {
            return cacheKey.Value;
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

比较它Cache.Remove:

public object Remove(string key)
{
    CacheKey cacheKey = new CacheKey(key, true);
    return this._cacheInternal.DoRemove(cacheKey, CacheItemRemovedReason.Removed);
}
Run Code Online (Sandbox Code Playgroud)

CacheInternal.DoRemove:

internal object DoRemove(CacheKey cacheKey, CacheItemRemovedReason reason)
{
    object obj2;
    this.UpdateCache(cacheKey, null, true, reason, out obj2);
    return obj2;
}
Run Code Online (Sandbox Code Playgroud)

最后Cache.Remove("key")比阅读更容易阅读Cache["key"] = null

  • Cache ["key"] = null将抛出ArgumentNullException - 这与"stress"无关. (2认同)