I want to use this memory cache to implement a lock to avoid http api replay, below is my demo code:
string cacheKey = "some_cache_key";
if (_cache.TryGetValue(cacheKey, out string val))
{
return BadRequest();
} else {
_cache.Set(cacheKey, "locked", DateTime.Now.AddSeconds(10));
}
If TryGetValue
is thread safe then only the first request can pass and other requests would fail.
⚠Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
Hello! Thanks for contacting us. This sounds like a general question about using ASP.NET Core. While we try to look at and respond to all issues, for questions like this we recommend posting to a community support group like Stack Overflow with the asp.net-core
tag.
this article should discuss the thread safety of the in memory cache though
I was wondering the same thing. I checked the source code and I found that the MemoryCache class uses the ConcurrentDictionary class as the internal cache, which is a thread safe dictionary.
The dictionary is thread safe, but the value is not. What if you cache say "Doctor" object by some key, then get it from cache and try to mutate it (per business logic), - you are mutating a process global variable which leads to crash. And you may need to mutate it, say to do a what-if algorithm based on cached value with some changed fields. We store objects in byte[] with transparent serialization (using Azos Pile), that's why every Get from cache gives us a fresh unique instance, otherwise the semantic of process-global class is dangerous to say the least.
Thanks for contacting us. We believe that the question you've raised have been answered. If you still feel a need to continue the discussion, feel free to reopen it and add your comments.
Most helpful comment
I was wondering the same thing. I checked the source code and I found that the MemoryCache class uses the ConcurrentDictionary class as the internal cache, which is a thread safe dictionary.