LazyCache
LazyCache copied to clipboard
Allow null values to be cached and refine TryGet method (see #155)
I have introduced the following changes:
- now the
IAppCache.Addmethod allows to cachenullvalues. No exception is thrown. - changed the signature of
IAppCache.TryGetValuefrombool TryGetValue<T>(string key, out object value);tobool TryGetValue<T>(string key, out T value); - modified the implementation of
IAppCache.TryGetValueso that values cached by usingIAppCache.GetOrAddand / orIAppCache.GetOrAddAsyncare handled correctly (the actual cached value is returned insted of the lazy wrapper). - augmented the IAppCache interface with the method
bool TryGetValueAsync<T>(string key, out Task<T> value);used to try fetch values cached by usingIAppCache.GetOrAddAsync
See issue #155 for the details.
Using the IAppCache.TryGetValueAsync method is quite convoluted.
Consider this example:
var cache = new CachingService();
const string key = "my-key";
await cache.GetOrAddAsync(key, async () =>
{
await Task.Delay(100);
return "cached value";
}
_ = cache.TryGetValueAsync(key, out var taskForFetchedValue);
var fetchedValue = await taskForFetchedValue; // fetched value is the string "cached value"
The API used must await the Task<T> obtained via the out parameter. Unfortunately we can't await the task for him, by providing an async implementation of IAppCache.TryGetValueAsync, because out parameters are not allowed in async methods.
I'm not a big fan of output parameters, because they are basically parameters used to return values outside of a method. Some people consider them as a bad practice. We can maybe consider to refactor the signature of both IAppCache.TryGetValue and IAppCache.TryGetValueAsync, so that tuples are used instead of out parameters:
(bool wasKeyFound, T value) TryGetValue<T>(string key);
Task<(bool wasKeyFound, T value)> TryGetValueAsync<T>(string key);
By doing so, we can write an async implementation of TryGetValueAsync and await the task on behalf of the API user.
Hi, any news on this ? Did you take a canche to review ?