Skip to content

Instantly share code, notes, and snippets.

@litodam
Last active August 2, 2017 19:32
Show Gist options
  • Save litodam/f0b9daf390e5e305cd39d32d6f893bb9 to your computer and use it in GitHub Desktop.
Save litodam/f0b9daf390e5e305cd39d32d6f893bb9 to your computer and use it in GitHub Desktop.
MemoryCacheHelper<T>
using System;
using System.Runtime.Caching;
using System.Threading.Tasks;
namespace Helpers
{
public static class MemoryCacheHelper
{
public const int DefaultMinutesToCache = 60;
public static T TryGetFromCache<T>(string cacheKey, Func<T> primeCacheFunc)
{
T value = Get<T>(cacheKey);
if (value == null)
{
value = primeCacheFunc();
Set(cacheKey, value, DefaultMinutesToCache);
}
return value;
}
public static async Task<T> TryGetFromCacheAsync<T>(string cacheKey, Func<Task<T>> primeCacheFunc)
{
T value = Get<T>(cacheKey);
if (value == null)
{
value = await primeCacheFunc();
Set(cacheKey, value, DefaultMinutesToCache);
}
return value;
}
private T Get<T>(string cacheKey)
{
return (T)MemoryCache.Default.Get(cacheKey);
}
private void Set<T>(string cacheKey, T value, int minutesToCache)
{
MemoryCache.Default.Set(cacheKey, value, DateTime.Now.AddMinutes(minutesToCache));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment