[転載]C#のオリジナルキャッシュを簡単に実現
1843 ワード
キャッシュインタフェースクラス:
インタフェースの実装:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo.Code
{
public interface ICache
{
T GetCache(string cacheKey) where T : class;//
void WriteCache(T value, string cacheKey) where T : class;//
void WriteCache(T value, string cacheKey, DateTime expireTime) where T : class;//
void RemoveCache(string cacheKey);//
void RemoveCache();//
}
}
インタフェースの実装:
using System;
using System.Collections;
using System.Web;
namespace Demo.Code
{
public class Cache : ICache
{
private static System.Web.Caching.Cache cache = HttpRuntime.Cache;
public T GetCache(string cacheKey) where T : class
{
if (cache[cacheKey] != null)
{
return (T)cache[cacheKey];
}
return default(T);
}
public void WriteCache(T value, string cacheKey) where T : class
{
cache.Insert(cacheKey, value, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration);
}
public void WriteCache(T value, string cacheKey, DateTime expireTime) where T : class
{
cache.Insert(cacheKey, value, null, expireTime, System.Web.Caching.Cache.NoSlidingExpiration);
}
public void RemoveCache(string cacheKey)
{
cache.Remove(cacheKey);
}
public void RemoveCache()
{
IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
cache.Remove(CacheEnum.Key.ToString());
}
}
}
}