473,586 Members | 2,491 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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="Web Form1.aspx.cs"
AutoEventWireup ="false" Inherits="TestS qlState.WebForm 1" %>
<!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="Micros oft
Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript"
content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.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.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
using System.Threadin g;
using System.Timers;

namespace TestSqlState
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Labe l
lbl;

private Thread m_Thread = null;
private void Page_Load(objec t sender,
System.EventArg s e)
{
lock(Session.Sy ncRoot)
{
if(Session["lbl"] == null)
Session["lbl"]
= "Start";

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

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

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

private void t1()
{
System.Timers.T imer TimeOutTimer =
new System.Timers.T imer(2000);
ElapsedEventHan dler
TimeOutDelegate = new ElapsedEventHan dler
(TimeOutEventPr ocessor);
TimeOutTimer.El apsed +=
TimeOutDelegate ;
TimeOutTimer.En abled = true;
}

private void TimeOutEventPro cessor(Object
myObject, ElapsedEventArg s TimeOutArgs)
{
lock(Session.Sy ncRoot)
{
Session["lbl"] = (string)
Session["lbl"] + "<br>Timer. ..";
}
}

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

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

}
#endregion
}
}

Nov 17 '05 #1
6 5422
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*******@disc ussions.microso ft.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="Web Form1.aspx.cs"
AutoEventWireup ="false" Inherits="TestS qlState.WebForm 1" %>
<!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="Micros oft
Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript"
content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.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.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
using System.Threadin g;
using System.Timers;

namespace TestSqlState
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Labe l
lbl;

private Thread m_Thread = null;
private void Page_Load(objec t sender,
System.EventArg s e)
{
lock(Session.Sy ncRoot)
{
if(Session["lbl"] == null)
Session["lbl"]
= "Start";

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

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

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

private void t1()
{
System.Timers.T imer TimeOutTimer =
new System.Timers.T imer(2000);
ElapsedEventHan dler
TimeOutDelegate = new ElapsedEventHan dler
(TimeOutEventPr ocessor);
TimeOutTimer.El apsed +=
TimeOutDelegate ;
TimeOutTimer.En abled = true;
}

private void TimeOutEventPro cessor(Object
myObject, ElapsedEventArg s TimeOutArgs)
{
lock(Session.Sy ncRoot)
{
Session["lbl"] = (string)
Session["lbl"] + "<br>Timer. ..";
}
}

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

/// <summary>
/// Required method for Designer support -
do not modify
/// the contents of this method with the
code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new
System.EventHan dler(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.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
using System.Threadin g;
using System.Timers;

namespace TestSqlState
{
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Labe l lbl;
private Thread m_Thread = null;

private void Page_Load(objec t sender, System.EventArg s e)
{
lock(Session.Sy ncRoot)
{
if(Session["lbl"] == null)
{
Session["lbl"] = "Start";
Thread.Sleep(10 0);
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(10 00);
lock(Session.Sy ncRoot)
{
Session["lbl"] = (string) Session["lbl"] + "<br>Cycle: "
+ i.ToString() + " ";
}
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
InitializeCompo nent();
base.OnInit(e);
}

private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);
}
#endregion
}
}


"Alvin Bruney" <vapordan_spam_ me_not@hotmail_ no_spamhotmail. com> wrote in
message news:uu******** ******@tk2msftn gp13.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.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
using System.Threadin g;
using System.Timers;

namespace TestSqlState
{
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Labe l lbl;
private Thread m_Thread = null;

private void Page_Load(objec t sender, System.EventArg s e)
{
lock(Session.Sy ncRoot)
{
if(Session["lbl"] == null)
{
Session["lbl"] = "Start";
Thread.Sleep(10 0);
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(10 00);
lock(Session.Sy ncRoot)
{
Session["lbl"] = (string) Session["lbl"] + "<br>Cycle: "
+ i.ToString() + " ";
}
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
InitializeCompo nent();
base.OnInit(e);
}

private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);
}
#endregion
}
}


"Alvin Bruney" <vapordan_spam_ me_not@hotmail_ no_spamhotmail. com> wrote in
message news:uu******** ******@tk2msftn gp13.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#******** *****@TK2MSFTNG P11.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.P age
{
protected System.Web.UI.W ebControls.Labe l lbl;
private Thread m_Thread = null;

private void Page_Load(objec t sender, System.EventArg s e)
{
lock(Session.Sy ncRoot)
{
if(Session["lbl"] == null)
{
Session["lbl"] = "Start";
Thread.Sleep(10 0);
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(10 00);
lock(Session.Sy ncRoot)


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.saunder s at surfcontrol.com > wrote in message
news:uw******** ******@TK2MSFTN GP12.phx.gbl...
"Ilia" <no****@hotmail .com> wrote in message
news:u#******** *****@TK2MSFTNG P11.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.P age
{
protected System.Web.UI.W ebControls.Labe l lbl;
private Thread m_Thread = null;

private void Page_Load(objec t sender, System.EventArg s e)
{
lock(Session.Sy ncRoot)
{
if(Session["lbl"] == null)
{
Session["lbl"] = "Start";
Thread.Sleep(10 0);
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(10 00);
lock(Session.Sy ncRoot)
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******** ******@TK2MSFTN GP09.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
3213
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 go to is a login form, which will set several session variables with the name used to log in, appropriate security level and some other misc...
4
4953
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. Dataset is retrieved and updated periodically. Eventually the dataset is sent to a web service for processing.
9
2372
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 - perhaps I'm just not very smart or perhaps MS is making this too hard for us sql bunnies to understand - I dunno, but I'd really appreciate someone...
8
8396
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
3435
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 session object (using state service). I'd like to start breaking out our functionality into component projects, but I'd like to get this session...
10
3495
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 more time I have on a session? If I do a refresh, does reset the session clock? Do you have have to go to another page to reset the session timeout...
2
2937
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 session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same. If the server is...
11
3631
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 method has the WebMethodAttribute.EnableSession set to true. When I run the test page the session is maintained. However, using a console...
4
2326
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, setting the Session.Timeout property doesn't help me avoid errors (I can obviously set the value to a very high value, but that still doesn't...
0
8204
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6617
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5392
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3838
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1184
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.