Open EnricoMassone opened 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 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 ?
I have introduced the following changes:
IAppCache.Add
method allows to cachenull
values. No exception is thrown.IAppCache.TryGetValue
frombool TryGetValue<T>(string key, out object value);
tobool TryGetValue<T>(string key, out T value);
IAppCache.TryGetValue
so that values cached by usingIAppCache.GetOrAdd
and / orIAppCache.GetOrAddAsync
are handled correctly (the actual cached value is returned insted of the lazy wrapper).bool TryGetValueAsync<T>(string key, out Task<T> value);
used to try fetch values cached by usingIAppCache.GetOrAddAsync
See issue #155 for the details.