1 Star 0 Fork 33

码云007/NScript

forked from 车江毅/NScript 
Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
StringParser.cs 1.68 KB
Copy Edit Raw Blame History
车江毅 authored 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/jamesma/NScript.git
git@gitee.com:jamesma/NScript.git
jamesma
NScript
NScript
master

Search