Automatically re-populate the cache at expiry time

前端 未结 4 1160
悲哀的现实
悲哀的现实 2021-02-09 14:52

I currently cache the result of a method invocation.

The caching code follows the standard pattern: it uses the item in the cache if it exists, otherwise it calculates t

4条回答
  •  终归单人心
    2021-02-09 15:07

    Here's a cache that never expires anything:

    var cache = new ConcurrentDictionary();
    
    var value = cache.GetOrAdd(someKey, key => MyMethod(key));
    

    Does that help?


    Here's a cache that never expires anything and refreshes the value after a certain lifetime:

    var cache = new ConcurrentDictionary>();
    
    var value = cache.AddOrUpdate(someKey,
                 key => Tuple.Create(MyMethod(key), DateTime.Now),
        (key, value) => (value.Item2 + lifetime < DateTime.Now)
                      ? Tuple.Create(MyMethod(key), DateTime.Now)
                      : value)
                      .Item1;
    

    Does that help?

提交回复
热议问题