7

I have multiple windows services running, which are on different processes, is the System.Runtime.Caching.MemoryCache common for these processes or is it separate instance for each process?

If not, is there a caching mechanism that shares the same instance of cache namespace on .net in a server.

I am not looking for distributed caching like redis. I want to share the in memory cache within ONE server but with multiple processes so its much faster, rather than going over network to another server and getting the data, deserializing it, etc.

MoXplod
  • 3,813
  • 6
  • 36
  • 46

2 Answers2

4

The System.Runtime.Caching.MemoryCache only works within a single process. Your best solution is to use a distributed cache (like Redis, Memcache, ...) with a single server (the server you are running your apps on).

C# objects can't be directly passed across process spaces, so there is inevitably some sort of serialization that will happen.

John Koerner
  • 37,428
  • 8
  • 84
  • 134
4

MemoryCache does not allow you to share memory between processes as the memory used to cache objects is bound to the application pool. That's the nature of any in-memory cache implementation you'll find.

The only way to actually use a shared cache is to use a distributed cache.

However, there are ways to share memory in C# but that's not actual caching anymore. You can use memory mapped files for example, as pointed out in an older answer here sharing memory between two applications

Community
  • 1
  • 1
MichaC
  • 13,104
  • 2
  • 44
  • 56
  • Memory mapped files - That sounds like it would be much slower than Runtime.MemoryCache. Have you used that before in a production environment? – MoXplod Feb 02 '17 at 01:39
  • No, I don't know how fast it is. I'm usually using either a database or redis plus in-memory cache in-front of it => http://cachemanager.net . – MichaC Feb 02 '17 at 09:45
  • Think we had a chat in your site as well :) I am building a local cache on top of redis too based on the backplane, but wanted to share the local cache amongst the different processes that run on the same machine. Instead of having duplicate copies in each process. – MoXplod Feb 02 '17 at 22:04
  • Ah that's funny ;) Let me know when you find a solution. – MichaC Feb 02 '17 at 22:47