캐시에 datetime을 저장해야합니다. 이렇게하면 만료 된 항목을 테스트 할 수 있습니다. 항목이 없거나 만료 된 경우? 그것에 대한 resolve 함수를 호출하십시오. 당신은 몇 가지 예외 처리를 만들 필요가
class Program
{
static string RetreiveFileContent(string filename)
{
if(!File.Exists(filename))
return default(string);
return File.ReadAllText(filename);
}
static void Main(string[] args)
{
var textFileCache = new MyCache<string, string>(TimeSpan.FromMinutes(2), RetreiveFileContent);
var content = textFileCache["helloworld.txt"];
// sometimes you need to cleanup old data.
textFileCache.Cleanup();
}
}
: 캐싱 textfiles에 대한
public class MyCache<TKey, TValue>
{
// type to store datetime and a value
private struct CacheItem
{
public DateTime RetreivedTime;
public TValue Value;
}
// the dictionary
private Dictionary<TKey, CacheItem> _cache = new Dictionary<TKey, CacheItem>();
private TimeSpan _timeout;
private Func<TKey, TValue> _resolveFunc;
public MyCache(TimeSpan timeout, Func<TKey, TValue> resolveFunc)
{
// store to fields
_timeout = timeout;
_resolveFunc = resolveFunc;
}
public TValue this[TKey key]
{
get
{
CacheItem valueWithDateTime;
// if nothing is found, you should resolve it by default
var getNewValue = true;
// lookup the key
if (_cache.TryGetValue(key, out valueWithDateTime))
// test if the value RetreivedTime was expired?
getNewValue = valueWithDateTime.RetreivedTime.Add(_timeout) > DateTime.UtcNow;
// was it found? or expired?
if (getNewValue)
{
valueWithDateTime = new CacheItem { RetreivedTime = DateTime.UtcNow, Value = _resolveFunc(key) };
_cache[key] = valueWithDateTime;
}
// return the value
return valueWithDateTime.Value;
}
}
// the cleanup method, you should call it sometimes...
public void Cleanup()
{
var currentDateTime = DateTime.UtcNow;
// ToArray prevents modifying an iterated collection.
foreach (var keyValue in _cache.ToArray())
if (keyValue.Value.RetreivedTime.Add(_timeout) < currentDateTime)
_cache.Remove(keyValue.Key);
}
}
예 : 여기
는 콜백 함수를 호출하여 그것을 자기를 채울 수있는 캐시의 예 ofcourse ....
새로운 유형 (CacheItem 어쩌면?)을 만들고 t 그는 사전 >'을 사용합니다. 'CacheItem '타입은'T' (값이 무엇이든간에)와 캐시에 값이 추가 된 시간을 추적하는'DateTime'을 포함합니다. 그런 다음 캐시 된 값이 반환되기 전에 유효한지 여부를 확인하고 다시 평가해야하는지 결정할 수 있습니다. –
itsme86
MemoryCache를 사용하지 않는 이유는 무엇입니까? Microsoft는 최근에 MemoryCache를 예전의 수하물이없는 네임 스페이스로 옮겼습니다. https://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache(v=vs.110).aspx – mageos
캐시 된 값을 추적하기 위해 Datetime을 어떻게 만들 수 있습니까? –