gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:09:40 25 4
gpt4 key购买 nike

  1. 如果我通过赋值插入缓存:

    缓存["键"] = 值;

    过期时间是多少?

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

    我想通过 if(Cache["key"]!=null) 检查值是否在缓存中,是否通过 Cache.Remove( "key")Cache["key"]=null ?

-- 编辑--

尝试Cache.RemoveCache["key"]=null 后,请勿使用Cache["key"]=null,因为它会在压力下使用时抛出异常。

最佳答案

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

MSDN Cache.Insert - method (String, Object):

This method will overwrite an existing cache item whose key matches the key parameter. The object added to the cache using this overload of the Insert method is inserted with no file or cache dependencies, a priority of Default, a sliding expiration value of NoSlidingExpiration, and an absolute expiration value of 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);
}

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;
}
}

Cache.Remove 比较:

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

CacheInternal.DoRemove:

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

最后,Cache.Remove("key")Cache["key"] = null

更具可读性

关于C# - 从缓存中插入和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2871572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com