Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Runtime.Caching.MemoryCache is it shared across processes in the same server

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.

like image 482
MoXplod Avatar asked Jan 31 '17 03:01

MoXplod


2 Answers

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.

like image 127
John Koerner Avatar answered Oct 25 '22 17:10

John Koerner


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

like image 36
MichaC Avatar answered Oct 25 '22 19:10

MichaC