我有一个网页缓存一些查询字符串值30秒,以便它不会收到重复的值.我使用以下课程:
public class MyCache {
private static ObjectCache cache = MemoryCache.Default;
public MyCache() { }
public void Insert(string key, string value)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.Priority = CacheItemPriority.Default;
policy.SlidingExpiration = new TimeSpan(0, 0, 30);
policy.RemovedCallback = new CacheEntryRemovedCallback(this.Cacheremovedcallback);
cache.Set(key, value, policy);
}
public bool Exists(string key)
{
return cache.Contains(key);
}
public void Remove(string key)
{
cache.Remove(key);
}
private void Cacheremovedcallback(CacheEntryRemovedArguments arguments)
{
FileLog.LogToFile("Cache item removed. Reason: " + arguments.RemovedReason.ToString() + "; Item: [" + arguments.CacheItem.Key + ", " + arguments.CacheItem.Value.ToString() + "]");
}
}
Run Code Online (Sandbox Code Playgroud)
这已经工作了几个星期,然后突然缓存不再保持值.将项目插入缓存后,CacheRemoved回调会立即触发,我得到删除的原因:CacheSpecificEviction 这是在带有.NET 4.0的Windows Server 2008 SP1 IIS7.5上运行的.在此期间,未对操作系统或IIS进行任何更改.
有没有办法解决这个问题,如果没有,是否有更好的缓存解决方案可以在网页中使用?
先感谢您.
Mar*_*ris -1
试试这个:
policy.AbsoluteExpiration = DateTime.Now.AddSeconds(30);
Run Code Online (Sandbox Code Playgroud)
这就是我使用缓存的方式:
public static class CacheHelper
{
private static ObjectCache _cache;
private const Double ChacheExpirationInMinutes = 10;
/// <summary>
/// Insert value into the cache using
/// appropriate name/value pairs
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="entity">item cached</param>
/// <param name="key">Name of item</param>
public static void Add<T>(T entity, string key) where T : class
{
if (_cache == null)
{
_cache = MemoryCache.Default;
}
if (_cache.Contains(key))
_cache.Remove(key);
CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddMinutes(ChacheExpirationInMinutes);
_cache.Set(key, entity, cacheItemPolicy);
}
/// <summary>
/// Remove item from cache
/// </summary>
/// <param name="key">Name of cached item</param>
public static void Clear(string key)
{
if (_cache == null)
{
_cache = MemoryCache.Default;
return;
}
_cache.Remove(key);
}
/// <summary>
/// Retrieve cached item
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="key">Name of cached item</param>
/// <returns>Cached item as type</returns>
public static T Get<T>(string key) where T : class
{
if (_cache == null)
{
_cache = MemoryCache.Default;
}
try
{
return (T)_cache.Get(key);
}
catch
{
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3737 次 |
| 最近记录: |