using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Api.Framework.Tools
{
///
/// 自定义内存缓存助手
///
public sealed class CacheTool
{
#region 单例模式
//创建私有化静态obj锁
private static readonly object _ObjLock = new object();
//创建私有静态字段,接收类的实例化对象
private static volatile CacheTool _CacheTool = null;
//构造函数私有化
private CacheTool() { }
//创建单利对象资源并返回
public static CacheTool GetSingleObj()
{
if (_CacheTool == null)
{
lock (_ObjLock)
{
if (_CacheTool == null)
_CacheTool = new CacheTool();
}
}
return _CacheTool;
}
#endregion
///
/// 缓存字典 => 【key|value|time】
///
private static volatile ConcurrentDictionary> _CacheDictionary = new ConcurrentDictionary>();
///
/// 1.主动过期
///
static CacheTool()
{
Task.Run(() =>
{
while (true)
{
Thread.Sleep(1000 * 60); //1分钟检查一次
if (_CacheDictionary != null && _CacheDictionary.Keys.Count > 0)
{
var listKey = new List();
foreach (var key in _CacheDictionary.Keys)
{
listKey.Add(key);
}
foreach (var key in listKey)
{
var valueTime = _CacheDictionary[key];
if (valueTime.Value < DateTime.Now)
_CacheDictionary.TryRemove(key, out KeyValuePair