bitfaster / BitFaster.Caching

High performance, thread-safe in-memory caching primitives for .NET

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add Put Method

paulhickman-a365 opened this issue · comments

Hi,

Would you consider adding an ICache.Put(K key, V value) method to add or replace an item in the cache without using a callback to retrieve it.

From reading your documentation, it looks like the GetOrAdd method assumes that the lambda will always be successful in getting an item to add. I could throw an exception from the callback, but that has poor performance (unless returning a null value prevents the key being stored?)

Also, there are situations where you know the old value for a key is out of date and already have the replacement value to hand.

Agree this is useful - I will look at adding two methods:

  • TryUpdate(key, value)
  • AddOrUpdate(key, value)

The first option can be used in cases where you know a value is changed, but not whether it is cached. So you can try to update it, and if it's not cached the cache will not be polluted.

The second option is effectively a Put, and could be used to seed the cache as you described.

Regarding the GetOrAdd method and the lambda throwing an exception - if it throws nothing is cached and the exception is not caught by the cache code, I assume the caller would catch and take steps to recover. I haven't tried but believe if the lambda returns null, null will be cached.

Those additions sound great

Merged implementations of both TryUpdate and GetOrAdd. They will be in the next package update.