在這樣的情況下,我使用了一個幫手:
public class CacheUtil
{
private static readonly object locker=new object();
public static T GetCachedItem<T>(string cacheKey,
Func<T> valueCreateFunc,
TimeSpan duration)
{
var expirationTime = DateTime.UtcNow + duration;
var cachedItem = HttpRuntime.Cache[cacheKey];
if (cachedItem == null)
{
lock(locker)
{
cachedItem = HttpRuntime.Cache[cacheKey];
if (cachedItem == null)
{
cachedItem = valueCreateFunc();
HttpRuntime.Cache.Add(cacheKey,
cachedItem,
null,
expirationTime,
Cache.NoSlidingExpiration,
CacheItemPriority.High,
null);
}
}
}
return (T) cachedItem;
}
}
,我會使用這樣的:
CacheUtil.GetCachedItem(
"someUniqueKey",
()=>{ //fetch resource from disk
return value;},
TimeSpan.FromDays(1)
)
提供的委託只會每天調用一次。如果該項目已在緩存中,則不會再次調用該委託。
您是否需要在運行時更改這些文件或者只是讀取它們? –