Session_End is called multiple times in the middle of the session

Am I using Session_End incorrectly?

In my application I have a cache to make the pages load faster, it works very well. Someone recently suggested to me that I would leak memory by never emptying it, and implement a method on Session_End that will clear any cache entries associated with that session ID.

Sometimes I started to see abnormal behavior. On page load, it is very rare that I see a blank page showing an exception due to the cache for that page being empty. I put a debugger breakpoint in cache access mode and session_end methods, hoping to catch it the next time it occurs.

The next time this happened, I was very surprised at what was actually happening. My browser was left open but idle for a long time, so I am assuming it had a stale session cookie. It hits the server for the page, which puts a copy of the page in the cache. While the page is still loading, Session_End is called instantly, which removes it from the cache. If I restart my browser, Session_End keeps getting calls, aggressively trying to close my session, which the poor browser is asking for.

So, I suppose my real questions are:

  • Why doesn't the browser get the new session cookie when the old one is anathema to IIS?
  • Is Session_End just not meant to be used this way?
  • Is there a better way to do what I am trying to do?

@Sosh - my global.asax.cs:

    protected void Session_End(Object sender, EventArgs e)
    {
        //clean up object cache on session expiry
        string sessionID = this.Session.SessionID;

        foreach (string key in Global.DataGroups.Keys)
        {
            if (key.EndsWith(sessionID))
            {
                Global.DataGroups.Remove(key);
            }
        }
    }

      

+2


source to share


1 answer


Yes, there is a better way. Use the built-in Cache object. It looks like you are reinventing the wheel ... The cache will be much more reliable. Just set the timeout to match the session timeout. If you need to reload the cache every 20 minutes, then what?



In general, I found that Session_End is a bit akin to Application_End in that you can never be sure when it will be called, and it sometimes comes across with intuition.

+1


source







All Articles