C# - Inserting and Removing from Cache
asp.net, c#, caching
Solution
1 `Cache["key"] = value` is equal to `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 It's better to remove values from cache by Cache.Remove("key"). If you use `Cache["key"] = null` it's equal to `Cache.Insert("key", null)`. Take a look at the `Cache.Insert` implementation:
public void Insert(string key, object value)
{
this._cacheInternal.DoInsert(true, key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true);
}
and `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;
}
}
Compare it to `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;
}
And finally `Cache.Remove("key")` is much more readble than `Cache["key"] = null`
Problem
If I insert to Cache by assigning the value: Cache["key"] = value; what's the expiration time? Removing the same value from Cache: I want to check if the value is in Cache by `if(Cache["key"]!=null)`, is it better to remove it from Cache by `Cache.Remove("key")` or `Cache["key"]=null` ? -- Edit -- After having tried `Cache.Remove` and `Cache["key"]=null`, DO NOT USE `Cache["key"]=null`, as it will throw exceptions when used in stress.