C # MemoryCache for two different types of keys?

I use MemoryCacheto store key / value pairs in my MVC.Net application.

There are two main goals that I use MemoryCache. One of them is to store sessions for user identifiers, and the other is to store constants (this is just an example). The keys can theoretically be the same in both cases, so I want to somehow separate them.

I think of 2 or 3 ways. Which way is superior? Or is there a better alternative?

  • Each key in the cache will be added to the namespace.

    "user_session: 1", "user_session: 2"
    "constants: 1", "constants: 2"

  • Using nested dictionaries as keys.

    The keyword "user_sessions" will appear, the value of which will be a Dictionary that maps identifiers to a session object. There will be key "constants" whose meaning will be the Dictionary.

  • Each "namespace" gets its own instance of MemoryCache.

The downside of # 2 is that when I want to get a value that belongs to the user ID, I need to get the dictionary first, and then get the value for the key in this dictionary. This means that I need to store the dictionary in memory.

IE:

Dictionary<string, string> userSessions = MemoryCache.Default["user_sessions"]
object session = userSessions.get("1");
+5
source share
2 answers

Go to option number 3!

  • It is easier for a programmer to access.
  • These are the fastest solutions (see comments for other solutions)
  • (. ).

№ 2:

  • .
  • , , .

№1:

  • ( )
  • .
  • , .
+2

, , MVC. . , , .

. , , , . , concurrency .

.

+1

All Articles