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

Allow null values to be cached and refine TryGet method (see #155) #157

Open EnricoMassone opened 3 years ago

EnricoMassone commented 3 years ago

I have introduced the following changes:

See issue #155 for the details.

EnricoMassone commented 3 years ago

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 outparameter. 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.

EnricoMassone commented 3 years ago

Hi, any news on this ? Did you take a canche to review ?