Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


Alternative to Session
.NET Session is very useful, but .NET implements a full lock on any page that needs to update session at some point in its lifecycle.
This means the user cannot load one page while another is posting back.

A solution is to store data in-memory on the server in a singleton Dictionary. You can use the session key of the user to store it by user. Then, change page session state to readonly to get past the session locking.

Here is a singleton for storing user data by session key. You could even use the logged in user id if you want to persist their data across multiple browsers and devices, since persisting it across 'multiple tabs' is pretty arbitrary anyway. However, if they are on multiple devices, they might be confused if the user experience in one device is updating the other!

Note this data is never explicitly removed. If your app restarts every few days, it will be cleared then. Otherwise you can clear this data on session end in global.asax.

/// <summary>
/// .NET session puts a page lock on every page that could write to it.
/// We are going to store common, non mission critical data in this memory session bag instead of relying on .NET session.
/// Then we can disable session on most pages and improve page performance.
/// </summary>
public class UserSessionBag
{
// Singleton implementation to ensure one item is in memory at all times.
private static volatile UserSessionBag instance;
private static object syncRoot = new Object();
private UserSessionBag() { }
public static UserSessionBag Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new UserSessionBag();
}
}
return instance;
}
}

Dictionary<string, object> dict = new Dictionary<string, object>();

/// <summary>
/// Get or set a value.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public object this[string key]
{
get
{
var current = System.Web.HttpContext.Current;
if (current == null || current.Session == null)
return null;
if (dict.ContainsKey(current.Session.SessionID + "~" + key))
return dict[current.Session.SessionID + "~" + key];
else
return null;
}
set
{
var current = System.Web.HttpContext.Current;
dict[current.Session.SessionID + "~" + key] = value;
}
}
} // class

Created By: amos 11/4/2014 6:15:38 PM
Updated: 5/10/2016 11:35:41 AM