1 Star 0 Fork 33

microinfo/NScript

forked from 车江毅/NScript 
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
StringParser.cs 1.68 KB
一键复制 编辑 原始数据 按行查看 历史
车江毅 提交于 2016-06-24 10:21 +08:00 . add project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BSF.BaseService.NScript.Core
{
/// <summary>
/// 字符串解析器
/// 缓存解析结果,加快下次解析
/// </summary>
public class StringParser<T>
{
private Dictionary<string, T> cache = new Dictionary<string, T>();
private readonly int recoverCount = 5000;//随机回收限制,未来替换为高性能的LRU
public void ClearCache()
{
lock (this)
{
cache.Clear();
}
}
public T Parser(string key, Func<T> func)
{
if (cache.ContainsKey(key))
{
return cache[key];
}
else
{
lock (this)
{
if (!cache.ContainsKey(key))
{
//随机回收一半
if (cache.Count > recoverCount)
{
List<string> recoverKeys = new List<string>(cache.Keys);
for (int i = 0; i < recoverCount / 2; i++)
{
int keyIndex = new Random(new Guid().GetHashCode()).Next(recoverKeys.Count);
cache.Remove(recoverKeys[keyIndex]);
recoverKeys.RemoveAt(keyIndex);
}
}
T t = func.Invoke();
cache.Add(key, t);
}
return cache[key];
}
}
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/microinfo/NScript.git
git@gitee.com:microinfo/NScript.git
microinfo
NScript
NScript
master

搜索帮助