ASPNET class lifecycle.

  • Thread starter Thread starter Scott Jacobsen
  • Start date Start date
S

Scott Jacobsen

I have a question about the lifecycle of an asp.net class. I have some
java background, so here's my question:

When I create a code behind class how are instance of that class
created/used, and what are the implications for member variable usage?

Is it like servlets - there is exactly one instance created, and
multiple threads access that instance? In that case member variables
must only be accessed in a thread safe manner because member variables
are shared among all the connections.

Is it like Enterprise Beans (I'm less familiar with these, but I think
the following is true) - there are several instances of the class
created and those instances are pooled. Each connection has access to
its own instance. So member variables are not shared among connections.

I guess my question boils down to - Can I do this:

public class WebForm1 : System.Web.UI.Page {
private bool m_calledFromClicked = false;

public void OnButtonClicked(object sender, EventArgs e) {
m_calledFromClicked = true;
DoSomething();
}

public void OnItemSelected(object sender, EventArgs e) {
m_calledFromClicked = false;
DoSomething();
}

private void DoSomething() {
// If we are like servlets, this is wrong, because m_calledFromClicked
//  could have been changed by another thread after OnButtonClicked set
//  it to true or OnItemSelected set it to false.
//
// If we are like enterprise beans this is OK, because we get our
//   own instance.
if (m_calledFromClicked) {
lblOutput.Text = "Called From Clicked";
}
else {
lblOutput.Text = "Not Called From Clicked";
}
}
}
 
Each code behind class is given one instatiation per request and is
destroyed after the response has been made, there for any member variables
you have are safe to manipulate from either the code behind class or the
derived aspx page.

MattC
 
Back
Top