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

CachingService.TryGetValue returning wrong value #176

Open Coder3333 opened 2 years ago

Coder3333 commented 2 years ago

I expect CachingService.TryGetValue to return the value that I stored in the cache, but instead, it returns the Lazy that was used to generate the value. I would expect a call to GetValueFromLazy in this method to make sure the right object is returned. You will see this behavior if you use GetOrCreate to initially store the value, and then follow up with TryGetValue to read the value.

Also, because this re-uses T when calling CacheProvider.TryGetValue, it never finds the value. You would need to use CacheProvider.TryGetValue to be able to fetch the value.

Here is the TryGetValue method from https://github.com/alastairtree/LazyCache/blob/master/LazyCache/CachingService.cs.

` public virtual bool TryGetValue(string key, out T value) { ValidateKey(key);

        return CacheProvider.TryGetValue(key, out value);
    }

`

alastairtree commented 2 years ago

Yeah this looks like a bug to me - thanks for submitting it. It should return the correctly typed object and unwrap the lazy using GetValueFromLazy in the same way the GetOrAdd does.

I assume this test is also broken somehow - https://github.com/alastairtree/LazyCache/blob/master/LazyCache.UnitTests/CachingServiceMemoryCacheProviderTests.cs#L1155

Would you be willing to submit a PR for the broken test and a fix?

phadtrapong commented 2 years ago

I have raise a PR to try fix this, Please feel free to share your feedback.