I'm looking at using a ConcurrentDictionary
to hold some cached data, which comes from a slow source (eg. a database).
The call to the database is async
. So, is it possible to have the concurrent dictionary call an async method if the item doesn't exist in the dictionary?
for example:
const int userId = 1;
var cachedUsers = new ConcurrentDictionary<int, Task<User>>();
var user = await cachedUsers.GetOrAdd(userId, val => GetSlowDbResultAsync(userId, cancellationToken));
so what that pseduo code above is trying to do is say:
- does User #1 exist in the C-Dict?
- Yes, ok, use that.
- No, grab user #1 from Db and stick it in the cache.
So - by putting the Task<User>
into the concurrent-dictionary's 'value' (for a key/value):
- is that ok?
- does the code I wrote above, an acceptable use of this or have I just abused everything that is sacred with async/await/c#
Notes:
This question is inspired from my question on twitter.
This is similar to a previous question I asked but didn't get much traction.