kreta/Kreta.Core/Cache.cs
2024-03-13 00:33:46 +01:00

62 lines
1.7 KiB
C#

using System;
using System.Diagnostics.Contracts;
using System.Runtime.Caching;
namespace Kreta.Core
{
public static class Cache
{
private static readonly MemoryCache DefaultCache = new MemoryCache("DefaultCache");
private static readonly CacheItemPolicy DefaultPolicy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromSeconds(30) };
[Pure]
public static Guid Add(object value)
{
var guid = Guid.NewGuid();
DefaultCache.Add(new CacheItem($"{guid}", value), DefaultPolicy);
return guid;
}
public static bool Add(string key, object value, CacheItemPolicy cacheItemPolicy)
{
return DefaultCache.Add(new CacheItem(key, value), cacheItemPolicy);
}
public static T AddOrGetExisting<T>(string key, T value, CacheItemPolicy cacheItemPolicy)
{
object existingValue = DefaultCache.AddOrGetExisting(key, value, cacheItemPolicy);
return (existingValue != null) ? (T)existingValue : value;
}
public static void Set(string key, object value, CacheItemPolicy cacheItemPolicy)
{
DefaultCache.Set(new CacheItem(key, value), cacheItemPolicy);
}
[Pure]
public static object Get(Guid guid)
{
return DefaultCache.Get($"{guid}");
}
[Pure]
public static object Get(string key)
{
return DefaultCache.Get(key);
}
[Pure]
public static void Remove(string key)
{
try
{
DefaultCache.Remove(key);
}
catch
{
throw;
}
}
}
}