Question

I am implementing a session structure.

I have a ConcurrentDictionary on server side holding on to all the <SessionId, UserSession> pairs.

When a new connection is established a cookie is assigned to a client browser, perm or temp depending on the RememberMe option.

When clients call the LogOut function it removes the session from the dictionary.

However, when the client browser is simply closed or crashed, and cookie was lost or expired or deleted, the server side session object in memory is remained in dictionary and becomes a ghost. Over time these ghosts will stack up.

My question is, how to improve the design so that the dead sessions can be cleaned up after they are expired?

I thought about making a timer service running a cleaning schedule, but it feels not elegant. Is there a simpler way to do this without depending on an external service?

Was it helpful?

Solution

i have similar situation in one of my project.

instead of dictionary, i used cache with a short absolute expiration and session id of user as my cache key:

HttpContext.Current.Cache.Insert(sessionID, userEntity, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero);

and in the client side, i make an ajax call,every 15 seconds, to notify the server and renew the cache for that session id.

so whenever a user close his browser window, server doesn't recieve any notification and session id of user expired automatically.

OTHER TIPS

If your sessionstate is "InProc", why not just apply your code in Session_Start and Session_End?

void Session_Start(object sender, EventArgs e)
{
    //Add to ConcurrentDictionary
}

void Session_End(object sender, EventArgs e)
{
    // Note: The Session_End event is raised only when the sessionstate mode
    // is set to InProc in the Web.config file. If session mode is set to StateServer 
    // or SQLServer, the event is not raised.

    //Remove from ConcurrentDictionary
}

I am answering my own question after few months. If I want to have a structure like that, I would use Microsoft SignalR. Because it controls the sessions for me in a real time manner and does much more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top