LazyCache - updating an entry

25 Views Asked by At

This question is about LazyCache.

I have code where I may have a list in the cache. If I do, I then need to add, update, or delete the entry in the list. Is the following the best way to do this? (I ask because this library may well have this built in.)

And I assume Add() works as an update.

public void CreateUser(AppUser user)
{
    lock (_userLock)
    {
        if ((!_cache.TryGetValue(nameof(Keys.Users), out List<UserFlyweight>? listUsers)) || listUsers is null)
            return;

        // replace with a new list so any code using the existing list does not have the last change as they're using it.
        listUsers = new List<UserFlyweight>(listUsers) { new UserFlyweight(user) };
        _cache.Add(nameof(Keys.Users), listUsers);
    }
}

Additional Questions:

  1. And, do I need to worry that one Task may be reading the list from the cache while this task is updating it? It's fine that the other Task may get the old or new list depending on timing, I just don't want it getting some indeterminate list. Or some other problem due to thread contention.
  2. If between the TryGetValue() and Add(), if the cache expires, I'm in trouble. Is there a way to say TryGetValueAndExtendTimeout(..., TimeSpan)? So I could pass TimeSpan.FromSeconds(5) and then be safe knowing the cache entry still exists.
0

There are 0 best solutions below