alastairtree / LazyCache

An easy to use thread safe in-memory caching service with a simple developer friendly API for c#
https://nuget.org/packages/LazyCache
MIT License
1.72k stars 159 forks source link

GetOrAdd / GetOrAddAsync<T> should return null if the item ADDED. #23

Closed PureKrome closed 6 years ago

PureKrome commented 7 years ago

Hi 👋

(edit: added repo and some more info)

Summary

Could the GetOrAddAsync<T> / GetOrAdd<T> methods return null if the item was ADDED. This is what Microsoft does with the ObjectCache.GetOrAdd(..) method so this would then follow the same logic.

Details

Ok, so in this code for GetOrAddAsync (or GetOrAdd...) you internally call the ObjectCache.AddOrExisting(..) under the hood to quietly add or get the item from the cache. Great!

Looking at the MS docs for OC.AOE it says (emphasis mine):

Return Value Type: System.Runtime.Caching.CacheItem If a cache entry with the same key exists, the specified cache entry; otherwise, null

which also is confirmed when I step through your code:

// CachingService.cs
var existingCacheItem = ObjectCache.AddOrGetExisting(key, newLazyCacheItem, policy);

existingCacheItem == null when the item was added. existingCacheItem != null when the item already exists and was retrieved.

It's also a nice hint to the developer to explain if the item was actually ADDED or RETRIEVED (exists). i.e.

So - what do you think?

Yes, this would be a major semver number increase/change.

--

How to repo:

alastairtree commented 7 years ago

Hi. Thanks for the suggestion. Wondering why you would want that/what problem it solves as i think that change would make the api less productive? The difference between LazyCache and ObjectCache is that in GetOrAddAsync we accept a delegate, not the actual value, so if we are adding to the cache the value has not been constructed yet. That means if we returned null you would not have a reference to it unless you kept hold of one in your delegate which feels messy to me. Or have I miss understood?

alastairtree commented 6 years ago

No reply for a while, closing.

PureKrome commented 6 years ago

Hi @alastairtree - it's been a while since I used this. So I can't remember the exact use case.

It was along the lines of something like:

the problem is the last step. I don't know if the item was added or just retrieved.

I think that's why I created this issue.

alastairtree commented 6 years ago

In that case the "record what happened" code can be done inside the callback as that only gets executed when the item is actually generated for the cache?

PureKrome commented 6 years ago

I understand what you're suggesting and think that has merit - I just wondered if I had problems with that when I last tried it?

Sample code or some updated docs with an example?