asp.net class lifecycle

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"; 
    }
  }
}
 
S

Saravana

For each request, an instance of class is created. So whatever you are
trying to do is possible
 

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