Last active
August 2, 2017 19:32
-
-
Save litodam/f0b9daf390e5e305cd39d32d6f893bb9 to your computer and use it in GitHub Desktop.
MemoryCacheHelper<T>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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