3

I prepared a very simple Web site to demonstrate this behavior.

It has one page with one Button and the following code:

public partial class TestStatic : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
        Class1.SetValue();
        Label1.Text = Class1.st.ToString();
    }
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
    Label1.Text = Class1.st.ToString();
  }
}

and one class:

public class Class1
{
  public Class1()
  {
  }
  public static int st = 0;
  public static void SetValue()
  {
    st = 1;
  }
}

So when the page is loaded you see in Label1 that st=1. If user clicks on the Buttton that sometimes you can see st=0 and sometimes st=1. In debugging I see that sometimes command

public static int st = 0;

is executed when an user clicks on the Button and this is a reason why st is changed to zero. This behavior I can reproduce in framework 4.5 only: it does not occur in framework 3.5. Can somebody explain me such behavior?

JJS
  • 6,431
  • 1
  • 54
  • 70
eug100
  • 177
  • 11

2 Answers2

5

Static data lives per application domain instance. Since the hosting (IIS) can unload application domains between web site calls, static data can be lost.

So, you really shouldn't rely on static in web apps.

Dennis
  • 37,026
  • 10
  • 82
  • 150
3

static values are shared across all instances of a class inside of a single App Domain. If you're using IIS Express, your appdomain may be getting recycled more often than you think it is.

reference this: Lifetime of ASP.NET Static Variable

Community
  • 1
  • 1
JJS
  • 6,431
  • 1
  • 54
  • 70
  • So, from reading that, the solution would be: 1) Class not an aspx page, 2) Not in App_Code dir and/or(?) 3) make class static. Are all 3 required? – tnw May 07 '13 at 20:12
  • What are you actually trying to accomplish? If you want to store global application state consider using Application["key"] = value; and var value = (int)Application["key"]. If this is just state you're trying to store for the current user, you should consider any number of things like Session, Cookies, or ViewState, depending on the scope of what you need. – JJS May 07 '13 at 20:16