Last post Nov 05, 2014 05:47 AM by Flash_Back
Nov 05, 2014 03:50 AM|Flash_Back|LINK
I'm currently working on a website project and facing some issues regarding global caching.
For instance, I have a database table "User" that I would like to cache, in order to prevent frequent database queries. I read lots of posts related to caching methods, but so far couldn't address this. Both static dictionaries and MemoryCache are cleared
whenever a response.redirect is called.
(I joined the code extracts below)
Is there any way to globally cache some database objects, which could be retrieved at any moment even with pages redirections ?
Thanks a lot !
Nov 05, 2014 03:57 AM|AidyF|LINK
Nov 05, 2014 04:33 AM|Flash_Back|LINK
Hello Aidy and thanks for your reply,
However as I said I already tried Cache and MemoryCache, used in a .cs file, not aspx page code file, but the thing is both are empty after a response.redirect call.
Right after the add method, the cache actually contains the "User" object, but after the page redirection, it doesn't contain it anymore.
It may be that I'm not using it correctly (in a .cs file instead of an aspx code file for example) but anyhow I can't retrieve the database whenever the page is changed. I wouldn't want it to be page related at all since this is a database object caching.
Nov 05, 2014 04:36 AM|AidyF|LINK
The cache should remain as long as you're in the same site. Are you redirecting to a different site?
Nov 05, 2014 04:50 AM|Flash_Back|LINK
No I don't, I know I must have made some silly mistake but really don't know where.
Here is the scenario:
I create a new User on CreateUser.aspx.cs :
protected void CreateUser_Click(object sender, EventArgs e)
User user = UserDao.Add(new User(myParameters));
Here is the UserDao.Add extract (the method adds the user object in database and in cache) :
static MemoryCache cache = new MemoryCache("Users");
public static User Add(User user)
string userKey = "Users_" + user.ID;
cache.Add(userKey , user, DateTimeOffset.MaxValue);
At this moment, the cache contains the user object.
Then the reponse.redirect is done and here is the UserProfile.aspx.cs code :
protected void Page_Load(object sender, EventArgs e)
user = UserDao.Get(userId);
And finally the UserDao.get method extract, which tried to get the object from cache and if it dosn't contain it, go retrieve it from database :
public static User Get (int userId)
string userKey = "Users_" + userId;
User user = ((User)cache.Get(userKey)); ...
Nov 05, 2014 05:01 AM|AidyF|LINK
Rather than using the static memorycache, just use
Nov 05, 2014 05:47 AM|Flash_Back|LINK
I just did so but same result unfortunately... The response.redirect definitely clears the cache, I'm quite desperate.