M
M
Mikhail Plyusnin2017-02-10 07:57:02
.NET
Mikhail Plyusnin, 2017-02-10 07:57:02

Caching data in server memory?

Good morning, this question is very interesting. The idea is that we have a repository pattern and wrap it with a cache, for example, it will be possible to implement this using MemoryCache . But this raises a number of other questions :

  1. Chief among them: How to synchronize cached data on changes (CRUD) of database records? Pull the cache, get the old data and add new ones there? Or completely clear the cache of changed data?
  2. Can there be problems accessing the cache from different threads? They write that MemoryCache is thread safe, no doubt, but if you just read data from the cache. But if you have one thread reading, and the other writes to the cache, you can’t do without locks.
  3. Maybe you shouldn't make a bike?
  4. Are there any ready-made and proven solutions to this issue?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Filatov, 2017-02-10
@rpe4a

1. In MemoryCache there is a concept of Expiration (Time of life of a piece of data). Those. you conditionally set how long to store the given object in the cache. Depends on your tasks. Let's say 5 minutes.
You set 5 minutes, for the object you put it in MemoryCache using the Add method.
Upon receipt, do Get - if the object has not expired, the object will be returned, if it has expired - get null - check for null - get data the old fashioned way, set Expiration again - and do Add again.
If you need to force clear - do Remove.
There is also the AddOrGetExisting method - it sort of combines the logic and simplifies the code.
2. To write from different threads, you need to write the implementation yourself. Here is an example - MemCache.cs
4. There are implementations of wrappers over MemoryCache, I can’t recommend anything. But they are in Google/github. Study.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question