0

I'm trying to fully understand the implications of thread safety in maintaining a BlockingCollection inside a MemoryCache

The scenario: log recent users that request any page from a site. Use an action filter on the controller to async log their user ID and the time of the request to a memory cache.

MemoryCache is thread safe, and BlockingCollection is thread safe. But how does a BlockingCollection within a MemoryCache work? Is this still thread safe?

My method of interest would look like:

private void logUser(int userID) {
    BlockingCollection<UserVisitLogItem> bc;
    if (_cache.TryGetValue("key", out bc)) {
        var user = bc.Where(x => x.UserID == userID).SingleOrDefault();
        if (user) {
            user.LatestVisitUTC = DateTime.UtcNow;
        } else {
            bc.Add(new UserVisitLogItem(userID, DateTime.UtcNow));
        }
    } 
}
jleach
  • 7,410
  • 3
  • 33
  • 60
  • Why are you using a `BlockingCollection`? This class is intended for producer-consumer scenarios. If you want a generic thread-safe container that can be searched for a specific item, your best option is probably the [`ConcurrentDictionary`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2) class. – Theodor Zoulias Mar 17 '21 at 14:20
  • Do you use the `MemoryCache` to access globally the `BlockingCollection`? – Peter Csala Mar 18 '21 at 07:19

0 Answers0