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));
}
}
}