using System.Runtime.Caching;
using System.Threading.Tasks;
namespace MemoryCacheLockingPattern
const string CacheKey = "cacheKey";
public static void Main(string[] args)
var credential = string.Empty;
Parallel.ForEach(Enumerable.Range(0, 100), (value) =>
credential = MemoryCacheHelper.GetCachedData<string>(CacheKey, 1, GenereateCredential);
Console.WriteLine(credential);
private static string GenereateCredential()
Console.WriteLine("產生憑証檔...");
public static class MemoryCacheHelper
private static object CacheLock = "cacheLock";
public static T GetCachedData<T>(string cacheKey, int expiredSeconds, Func<T> GetData) where T : class
T cachedData = MemoryCache.Default.Get(cacheKey, null) as T;
cachedData = MemoryCache.Default.Get(cacheKey, null) as T;
CacheItemPolicy policy = new CacheItemPolicy()
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(expiredSeconds))
MemoryCache.Default.Set(cacheKey, cachedData, policy);