【发布时间】:2018-10-02 05:19:53
【问题描述】:
对于高流量网站来说,以下功能是否是一种好的做法?是否存在任何类型的死锁或线程安全问题?
public static T GetInitializedTempCache<T>(string key, Func<T> getData, int minutes, bool skip = false)
{
if (!skip)
{
var value = HttpRuntime.Cache[key];
if (value == null || value.GetType() != typeof(T))
{
T data = getData();
if (data != null && Config.Debugging.EnableCaching)
{
HttpRuntime.Cache.Add(key, data, null, DateTime.Now.AddMinutes(minutes), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null);
}
return data;
}
return (T)value;
}
else
{
return getData();
}
}
public static void RemoveTempCacheContains(string key)
{
var keys = new List<string>();
var enumerator = HttpRuntime.Cache.GetEnumerator();
// copy all keys that currently exist in Cache
while (enumerator.MoveNext())
{
var cacheKey = (string)enumerator.Key;
if (cacheKey.Contains(key))
{
keys.Add(cacheKey);
}
}
for (int i = 0; i < keys.Count; i++)
{
HttpRuntime.Cache.Remove(keys[i]);
}
}
【问题讨论】:
-
如果您正在研究缓存,请查看github.com/App-vNext/Polly 项目,这是一个“弹性和瞬态故障处理库”。它可能会在您网站的其他方面为您提供帮助。
标签: .net performance caching iis thread-safety