简体   繁体   中英

Strange behavior of static variables in a web site

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM