C# Cache快取類的應用
阿新 • • 發佈:2020-12-15
提示:C# 中使用Cache快取資料
private static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
//獲取快取值
///key:快取對應的鍵值
public static object GetCacheValue(string key)
{
object val = null;
if (key != null && cache.TryGetValue (key, out val))
{
return val;
}
else
{
return default(object);
}
}
//設定快取值(預設快取時間)
public static void SetChacheValue(string key, object value)
{
if (key != null)
{
cache.Set(key, value, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromHours(1)
});
}
}
//設定快取值(可自己修改快取時間)
public static void SetChacheValue(string key, object value, int second)
{
if (key != null)
{
cache.Set(key, value, TimeSpan.FromSeconds(second));
}
}
//是否存在某快取值
public static bool Exists(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return cache.TryGetValue(key, out _);
}
//刪除快取值
public static void Remove(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
cache.Remove(key);
}