How can I use Cache in ASP.NET which is accessible by all users not just a specific user context while having a specific key of this cache removed automatically when a user closes the browser window or expires (like a session object) ?
-
Why common cache among all, but individual keys removed per user? Why not just use session?Brian Mains– Brian Mains2012-04-17 02:33:32 +00:00Commented Apr 17, 2012 at 2:33
-
Because I still want another user to be able to access that object as well !Ihab– Ihab2012-04-17 02:34:58 +00:00Commented Apr 17, 2012 at 2:34
-
You need to explain in more detail what you are trying to do. It is not clear and it will help in getting your answer. Can you edit your question and provide more details?agarcian– agarcian2012-04-17 02:39:44 +00:00Commented Apr 17, 2012 at 2:39
-
Ulises answered exactly what I wanted :) ThanksIhab– Ihab2012-04-17 02:41:21 +00:00Commented Apr 17, 2012 at 2:41
2 Answers
Cache is accessible to all users, you can set it to expire after a period of time:
Cache.Insert("key", myTimeSensitiveData, null,
DateTime.Now.AddMinutes(1), TimeSpan.Zero);
You may remove the cache entry whenever a session expires by implementing the global.asax's session end event
void Session_End(Object sender, EventArgs E)
{
Cache.Remove("MyData1");
}
See this for more details on Cache
Edited: Regarding your question on how to react when the user closes its browser, I think that this is not straightforward. You could try javascript on the client side to handle the "unload" event but this is not reliable since the browser/client may just crash. In my opinion the "heartbeat" approach would work but it requires additional effort. See this question for more info.
5 Comments
You'll have to use the Session_OnEnd() event to remove the item from the cache. However, this event will not fire if the user just closes the browser. The event will only fire on the session timeout. You should probably add a check to see if the item has already been removed:
public void Session_OnEnd()
{
// You need some identifier unique to the user's session
if (Cache["userID"] != null)
Cache.Remove("userID");
}
Also, if you want the item in the cache to stay active for the duration of the user's session, you'll need to use a sliding expiration on the item and refresh it with each request. I do this in the OnActionExecuted (ASP.NET MVC only).
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Put object back in cache in part to update any changes
// but also to update the sliding expiration
filterContext.HttpContext.Cache.Insert("userID", myObject, null, Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(20), CacheItemPriority.Normal, null);
base.OnActionExecuted(filterContext);
}