473,399 Members | 2,478 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

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

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
}
}

Nov 17 '05 #1
6 5406
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" <an*******@discussions.microsoft.com> wrote in message
news:0a****************************@phx.gbl...
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
}
}

Nov 17 '05 #2
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
}
}


"Alvin Bruney" <vapordan_spam_me_not@hotmail_no_spamhotmail.com > wrote in
message news:uu**************@tk2msftngp13.phx.gbl...
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
--

Nov 17 '05 #3
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
}
}


"Alvin Bruney" <vapordan_spam_me_not@hotmail_no_spamhotmail.com > wrote in
message news:uu**************@tk2msftngp13.phx.gbl...
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
--

Nov 17 '05 #4
"Ilia" <no****@hotmail.com> wrote in message
news:u#*************@TK2MSFTNGP11.phx.gbl...
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"] + "<br>Started..."; }
}
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.
--
John

--
John
Nov 17 '05 #5
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" <john.saunders at surfcontrol.com> wrote in message
news:uw**************@TK2MSFTNGP12.phx.gbl...
"Ilia" <no****@hotmail.com> wrote in message
news:u#*************@TK2MSFTNGP11.phx.gbl...
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"] +

"<br>Started...";
}
}


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.
--
John

--
John

Nov 17 '05 #6
"Ilia" <no****@hotmail.com> wrote in message
news:e8**************@TK2MSFTNGP09.phx.gbl...
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.
--
John

Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Paul Yanzick | last post by:
Hello, I am trying to develop a book tracking application for my capstone in school, and am running into a problem. The application is an ASP.Net application written in C#. The first page you...
4
by: DeeAnn | last post by:
We've encountered a "flaky" situation with a Session variable holding a data set on load balanced servers; server session with cookies is set up. Background: Session variable holds a dataset. ...
9
by: Greg Linwood | last post by:
I'm having difficulty understanding Session state in ASP.Net. It's almost embarrassing asking this as I've been using ASP since it was first released & it really shouldn't be this hard to use -...
8
by: karahan celikel | last post by:
I realized that when SqlServer mode is used for session management Session_End event is not fired in global.asax. What can I do if I want to do something when a user's session end? Thanks
3
by: Mark | last post by:
Ok, I know that .net inherently does not share session data across asp.net projects, but is there any decent work around to this. We already have a big chunk of our application using the asp.net...
10
by: tshad | last post by:
I have been using the default session state (InProc) and have found that I have been loosing my information after a period of time (normally 20 minutes). Is there anyway to find out how much...
2
by: DC | last post by:
Hi, we are using ASP.Net 1.1 on eight servers with one session state server (the windows 2003 service). Too often we are getting the exception "Unable to make the session state request to the...
11
by: Glenn | last post by:
Hi I've been experimenting with managing state using the Session object. I've created a simple WS with a couple of methods, one which sets a string value, another that retrieves it. Each...
4
by: Nathan Sokalski | last post by:
I have a page that uses Session variables when generating the SQL statements used to submit and retrieve data from a database. However, because I don't know how long the user will be on the page,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.