Session State does not Work with Multithreading and SQL Server - Bug???

I

Ilia

Hi folks,

I have some problems with ASP.NET Session State. The
following simple program runs well if the Session State
set as "InProc". If I switch to "SQLServer", the changes,
made by the second thread, are lost. Any idea?

I use VS.NET 2003 on Windows Server 2003 with hot fixes
(as of 30-Oct-2003) and SQL Server 2000 SP 3a.

Thanks.
Ilia

---- WebForm1.aspx
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="TestSqlState.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<META HTTP-EQUIV="Refresh" CONTENT="3;
URL=">
<meta name="GENERATOR" Content="Microsoft
Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript"
content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post"
runat="server">
<asp:Label id="lbl"
runat="server">Label</asp:Label>
</form>
</body>
</HTML>


---- WebForm1.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Timers;

namespace TestSqlState
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label
lbl;

private Thread m_Thread = null;


private void Page_Load(object sender,
System.EventArgs e)
{
lock(Session.SyncRoot)
{
if(Session["lbl"] == null)
Session["lbl"]
= "Start";

lbl.Text = (string) Session
["lbl"];
}

m_Thread = new Thread(new
ThreadStart(t1));
m_Thread.Start();

lock(Session.SyncRoot)
{
Session["lbl"] = (string)
Session["lbl"] + "<br>Started...";
}
}

private void t1()
{
System.Timers.Timer TimeOutTimer =
new System.Timers.Timer(2000);
ElapsedEventHandler
TimeOutDelegate = new ElapsedEventHandler
(TimeOutEventProcessor);
TimeOutTimer.Elapsed +=
TimeOutDelegate;
TimeOutTimer.Enabled = true;
}

private void TimeOutEventProcessor(Object
myObject, ElapsedEventArgs TimeOutArgs)
{
lock(Session.SyncRoot)
{
Session["lbl"] = (string)
Session["lbl"] + "<br>Timer...";
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required
by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support -
do not modify
/// the contents of this method with the
code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new
System.EventHandler(this.Page_Load);

}
#endregion
}
}
 
A

Alvin Bruney

You are violating a major threading rule here. Your worker thread must not
touch objects owned by the main thread. The session object is owned by the
main thread. One solution is to modify your thread constructor to accept a
httpcontext object and then pass a reference to the current cache instance
to the thread. You can modify it safely in there. I've not checked to see if
this is the only buggy thing in the code by the way but this one caught my
eye.

The reason it is working in the first place is entirely dependent on the
underlying platform. It should fail consistenly on XP or server but work
sometimes on lesser platforms.

regards
--


-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
Ilia said:
Hi folks,

I have some problems with ASP.NET Session State. The
following simple program runs well if the Session State
set as "InProc". If I switch to "SQLServer", the changes,
made by the second thread, are lost. Any idea?

I use VS.NET 2003 on Windows Server 2003 with hot fixes
(as of 30-Oct-2003) and SQL Server 2000 SP 3a.

Thanks.
Ilia

---- WebForm1.aspx
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="TestSqlState.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<META HTTP-EQUIV="Refresh" CONTENT="3;
URL=">
<meta name="GENERATOR" Content="Microsoft
Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript"
content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post"
runat="server">
<asp:Label id="lbl"
runat="server">Label</asp:Label>
</form>
</body>
</HTML>


---- WebForm1.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Timers;

namespace TestSqlState
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label
lbl;

private Thread m_Thread = null;


private void Page_Load(object sender,
System.EventArgs e)
{
lock(Session.SyncRoot)
{
if(Session["lbl"] == null)
Session["lbl"]
= "Start";

lbl.Text = (string) Session
["lbl"];
}

m_Thread = new Thread(new
ThreadStart(t1));
m_Thread.Start();

lock(Session.SyncRoot)
{
Session["lbl"] = (string)
Session["lbl"] + "<br>Started...";
}
}

private void t1()
{
System.Timers.Timer TimeOutTimer =
new System.Timers.Timer(2000);
ElapsedEventHandler
TimeOutDelegate = new ElapsedEventHandler
(TimeOutEventProcessor);
TimeOutTimer.Elapsed +=
TimeOutDelegate;
TimeOutTimer.Enabled = true;
}

private void TimeOutEventProcessor(Object
myObject, ElapsedEventArgs TimeOutArgs)
{
lock(Session.SyncRoot)
{
Session["lbl"] = (string)
Session["lbl"] + "<br>Timer...";
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required
by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support -
do not modify
/// the contents of this method with the
code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new
System.EventHandler(this.Page_Load);

}
#endregion
}
}
 
I

Ilia

Thank you for you response.

I have to do it so, as the main page is refreshed (and Page_Load is called)
every 3 seconds. I use the session object to save and pass the status to the
"new" page. There are several examples on the Net, which do it the same way.
On one server it works fine.

Now I have to move to a web farm. The only way, which I can use to save the
session information in this case, is a SQL Server as the page can be served
from different servers.I cannot use the cache or any other local (to a
server) objects.

The code below should be readable now.

Ilia




using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Timers;

namespace TestSqlState
{
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lbl;
private Thread m_Thread = null;

private void Page_Load(object sender, System.EventArgs e)
{
lock(Session.SyncRoot)
{
if(Session["lbl"] == null)
{
Session["lbl"] = "Start";
Thread.Sleep(100);
m_Thread = new Thread(new ThreadStart(t1));
m_Thread.Start();
}
lbl.Text = (string) Session["lbl"];
Session["lbl"] = (string) Session["lbl"] + "<br>Started...";
}
}

private void t1()
{
for(int i=0; i < 11; i++)
{
Thread.Sleep(1000);
lock(Session.SyncRoot)
{
Session["lbl"] = (string) Session["lbl"] + "<br>Cycle: "
+ i.ToString() + " ";
}
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
 
I

Ilia

Thank you for you response.

I have to do it so, as the main page is refreshed (and Page_Load is called)
every 3 seconds. I use the session object to save and pass the status to the
"new" page. There are several examples on the Net, which do it the same way.
On one server it works fine.

Now I have to move to a web farm. The only way, which I can use to save the
session information in this case, is a SQL Server as the page can be served
from different servers.I cannot use the cache or any other local (to a
server) objects.

The code below should be readable now.

Ilia




using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Timers;

namespace TestSqlState
{
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lbl;
private Thread m_Thread = null;

private void Page_Load(object sender, System.EventArgs e)
{
lock(Session.SyncRoot)
{
if(Session["lbl"] == null)
{
Session["lbl"] = "Start";
Thread.Sleep(100);
m_Thread = new Thread(new ThreadStart(t1));
m_Thread.Start();
}
lbl.Text = (string) Session["lbl"];
Session["lbl"] = (string) Session["lbl"] + "<br>Started...";
}
}

private void t1()
{
for(int i=0; i < 11; i++)
{
Thread.Sleep(1000);
lock(Session.SyncRoot)
{
Session["lbl"] = (string) Session["lbl"] + "<br>Cycle: "
+ i.ToString() + " ";
}
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
 
J

John Saunders

Ilia said:
The code below should be readable now.

This code is seriously broken. You're missing a fundamental fact about
ASP.NET. It is a request/response architecture. In particular, once the
response has been sent, the page object ALONG WITH YOUR THREAD are
destroyed.

....
namespace TestSqlState
{
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lbl;
private Thread m_Thread = null;

private void Page_Load(object sender, System.EventArgs e)
{
lock(Session.SyncRoot)
{
if(Session["lbl"] == null)
{
Session["lbl"] = "Start";
Thread.Sleep(100);
m_Thread = new Thread(new ThreadStart(t1));
m_Thread.Start();
}
lbl.Text = (string) Session["lbl"];
Session["lbl"] = (string) Session["lbl"] +

The above brace ends the Page_Load event handler. After that point
(considering that you have no other code) the Render phase will execute,
sending any HTML to the client. Next, the Unload phase will run and the page
will then be destroyed.
private void t1()
{
for(int i=0; i < 11; i++)
{
Thread.Sleep(1000);
lock(Session.SyncRoot)

But "Session" is Page.Session, and the Page may no longer be valid by the
time you get here - the request may be over!

Any multi-threaded code can seem to "work" - right up until the time when it
fails. In particular, if you're testing on a single-CPU system, then you're
not testing the code at all. Don't let the fact that "it works on one
machine" lead you to believe that your code is correct.
 
I

Ilia

Sorry, but I cannot agree with you.

The new thread m_Thread will survive, as the aplication that process
requests runs always and is not shut down after each page.

Microsft's ".NET Framework Developer's Guide" says about the Session State:
<quote>
ASP.NET provides the cross-request state information (shopping carts, data
scrolling, and so on) infrastructure that Web applications require, with
built-in session-state functionality that enables you to take the
following actions:
....
a.. Automatically identify and classify requests coming from a single
browser client into a logical application session on the server.
a.. Store session-scoped data on the server for use across multiple browser
requests.
</quote>

Yes, you can access the session object through Page.Session, but the
property gets the current Session object provided by ASP.NET, not create its
own. And again, .NET Framework Class Library Reference says:
<quote>
This property provides information about the current request's session. A
Session object is maintained for each user that requests a page or document
from an ASP.NET application. Variables stored in the Session object are not
discarded when the user moves from page to page in the application; instead,
these variables persist as long as the user is accessing pages in your
application.
</quote>

Anyway it works well with "InProc"-Session. After switch to
"SQLSever"-Session the old thread works well too, only the new thread lost
the information. It makes me suspicious.

Ilia





John Saunders said:
Ilia said:
The code below should be readable now.

This code is seriously broken. You're missing a fundamental fact about
ASP.NET. It is a request/response architecture. In particular, once the
response has been sent, the page object ALONG WITH YOUR THREAD are
destroyed.

...
namespace TestSqlState
{
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lbl;
private Thread m_Thread = null;

private void Page_Load(object sender, System.EventArgs e)
{
lock(Session.SyncRoot)
{
if(Session["lbl"] == null)
{
Session["lbl"] = "Start";
Thread.Sleep(100);
m_Thread = new Thread(new ThreadStart(t1));
m_Thread.Start();
}
lbl.Text = (string) Session["lbl"];
Session["lbl"] = (string) Session["lbl"] +

The above brace ends the Page_Load event handler. After that point
(considering that you have no other code) the Render phase will execute,
sending any HTML to the client. Next, the Unload phase will run and the page
will then be destroyed.
private void t1()
{
for(int i=0; i < 11; i++)
{
Thread.Sleep(1000);
lock(Session.SyncRoot)

But "Session" is Page.Session, and the Page may no longer be valid by the
time you get here - the request may be over!

Any multi-threaded code can seem to "work" - right up until the time when it
fails. In particular, if you're testing on a single-CPU system, then you're
not testing the code at all. Don't let the fact that "it works on one
machine" lead you to believe that your code is correct.
 
J

John Saunders

Ilia said:
Sorry, but I cannot agree with you.

The new thread m_Thread will survive, as the aplication that process
requests runs always and is not shut down after each page.

The thread will survive, but the request may well be over before the thread
is finished. The request will not wait for the thread to terminate before
the request ends. Microsoft does not specify what happens when a thread is
accessing resources allocated for a request after the request has ended.
Microsft's ".NET Framework Developer's Guide" says about the Session State:
<quote>
ASP.NET provides the cross-request state information (shopping carts, data
scrolling, and so on) infrastructure that Web applications require, with
built-in session-state functionality that enables you to take the
following actions:
...
a.. Automatically identify and classify requests coming from a single
browser client into a logical application session on the server.
a.. Store session-scoped data on the server for use across multiple browser
requests.
</quote>

Yes, but only during a request, not in between requests.
Yes, you can access the session object through Page.Session, but the
property gets the current Session object provided by ASP.NET, not create its
own. And again, .NET Framework Class Library Reference says:

My point was that you were using Page.Session, but the Page is gone!
<quote>
This property provides information about the current request's session.

Yes! Notice. "The current request". Your thread will be running when there
is no current request!
A
Session object is maintained for each user that requests a page or document
from an ASP.NET application. Variables stored in the Session object are not
discarded when the user moves from page to page in the application; instead,
these variables persist as long as the user is accessing pages in your
application.
</quote>

Anyway it works well with "InProc"-Session. After switch to
"SQLSever"-Session the old thread works well too, only the new thread lost
the information. It makes me suspicious.

No, it _appears_ to work well with "InProc". Have you tested it in an
environment which stresses multithreaded operations, like a fast multi-cpu
system, where your application is being stressed with a high load? If not,
then the fact that it hasn't "broken" yet doesn't imply that your code is
correct.

In fact, for your code to be correct, it must always be the case that you
can safely access "the current request's session" when there is no current
request. And then it will only be correct once you stop accessing Page.*,
including Page.Session, Page,Request, etc, since your thread will be
operating after the Page object is no longer valid.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top