DubMan
DubMan

Reputation: 460

MemoryCache over Threads

I'm currently investigating some code which has a cache layer which at the bottom level uses the MemoryCache class. This is a c# Windows Service app so not web/IIS. There is a section of the code which spawns off a number of threads in which it creates and executes some code in a POC to perform some calculations. These are then stored in the above mentioned cache layer. What is been seen is it looks like cached values seem to be getting stored per thread and not at apication level. I thought that MemoryCache was a Singleton that would sit out side of the individual threads.

Can anybody confirm this behaviour would be expected?

Many thanks for any comments.

Upvotes: 0

Views: 1479

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

A MemoryCache is thread-safe but there is no reason to assume it's a singleton. If you want different threads to access the same MemoryCache instance you need to give them all a reference to the same instance (either as a singleton (really bad) static (still bad) or through argument passing as dependency injection (good)).

The simple way to do it (which does use global state) is to access the default memory cache:

var cache = MemoryCache.Default; // not really a good idea and harder to test, works

You can find the specific docs here. Make sure to configure it in your app/web.config file.

Upvotes: 3

Related Questions