キャッシュに保存された日時を保存する必要があります。この方法でアイテムが期限切れになっているかどうかテストできます。アイテムが見つからないか、期限が切れていれば?そのためにresolve関数を呼び出します。ここで
は、コールバック関数を呼び出すことによって、自己それを埋めることができますキャッシュの例です:キャッシュテキストファイル用
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);
}
}
例:
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();
}
}
あなたは、いくつかの例外処理を作成する必要がありますofcourse ....
新しいタイプ(CacheItem多分?)を作成して、彼は辞書 '辞書>'です。 'CacheItem '型は 'T'(値が何であれ)を保持し、値がキャッシュにいつ追加されたかを記録する' DateTime'を保持します。次に、キャッシュされた値が返される前に有効かどうかを確認するだけで、再評価が必要かどうかを判断できます。 –
itsme86
MemoryCacheを使用してみませんか?マイクロソフトは最近、MemoryCacheを以前使用した手荷物のない名前空間に移行しました。 https://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache(v=vs.110).aspx – mageos
キャッシュされた値を追跡するためにDatetimeを作成するにはどうすればよいですか? –