I did some work that adds values ββto the Session state inside Thread. I would like these values ββto be available off-stream (obviously).
The information added to the session is available outside the session without any problems when the session state mode is βInProcβ.
However, when the session state mode is set to "StateServer", the behavior is different. Basically, the values ββset inside Thread are saved sometimes , and sometimes not . It seems random to me.
Here is the code that reproduces the problem.
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void store_Click(object sender, EventArgs e) { // Set the session values to default. Session["Test1"] = "No"; Session["Test2"] = "No"; // Set the Test1 session value in the thread. ThreadObject threadObject = new ThreadObject() { Username = Page.User.Identity.Name, SessionState = Session }; worker = new Thread(new ParameterizedThreadStart(Work)); worker.Start(threadObject); // Set the Test2 session value in this thread just to compare. Session["Test2"] = "Yes"; } protected void print_Click(object sender, EventArgs e) { // Print out the Session values. label1.Text = string.Empty; label1.Text += "Inside Thread: " + Session["Test1"] + ", \n"; label1.Text += "Outside: " + Session["Test2"] + "\n"; } private static Thread worker; public static void Work(object threadObject) { // Retrieve the Session object and set the Test2 value. ThreadObject threadObject1 = (ThreadObject)threadObject; HttpSessionState currentSession = threadObject1.SessionState; currentSession["Test1"] = "Yes"; } } public class ThreadObject { public string Username { get; set; } public HttpSessionState SessionState { get; set; } }
The above code works fine with SessionState = "InProc" mode, but is random with:
<sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" cookieless="false" timeout="20"/>
Any ideas?
EDIT: According to the comments below, the thread must end before the request is completed (main thread), otherwise everything that is added to the session will be lost. This is because at the end of the main thread, the session is serialized and sent to the data store (Out of Process or SQL Server).
source share