// *********************************************************************** // Assembly : Helper // Author : yubaolee // Created : 12-16-2016 // // Last Modified By : yubaolee // Last Modified On : 12-21-2016 // 使用微软默认带超时的Cache // File: CacheContext.cs // *********************************************************************** using System; using System.Collections.Concurrent; using Microsoft.Extensions.Caching.Memory; namespace Infrastructure.Cache { public class CacheContext : ICacheContext { private IMemoryCache _objCache; private static readonly ConcurrentDictionary> queueDic = new ConcurrentDictionary>(); public CacheContext(IMemoryCache objCache) { _objCache = objCache; } public override T Get(string key) { return _objCache.Get(key); } public override bool Set(string key, T t, DateTime expire) { var obj = Get(key); if (obj != null) { Remove(key); } _objCache.Set(key, t, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(expire)); //绝对过期时间 return true; } public override bool Remove(string key) { _objCache.Remove(key); return true; } /// /// 添加并发锁 /// /// 值 /// 执行方法 /// 键 /// public override async Task Lock(string id, Func> func, string key = "hc") { var queue = queueDic.GetOrAdd(id, new ConcurrentQueue()); var token = Guid.NewGuid().ToString(); queue.Enqueue(token); queue.TryPeek(out string newToken); if (token != newToken) { while (true) { Thread.Sleep(10); queue.TryPeek(out newToken); if (token == newToken) { break; } } } try { return await func(id); } finally { queue.TryDequeue(out string _); } } } }