Ihab
Ihab

Reputation: 2255

Using Cache ASP.NET

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) ?

Upvotes: 0

Views: 1256

Answers (2)

Ulises
Ulises

Reputation: 13419

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.

Upvotes: 6

mgnoonan
mgnoonan

Reputation: 7200

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);
}

Upvotes: 0

Related Questions