简体   繁体   English

网站中静态变量的奇怪行为

[英]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: 它有一个页面,一个Button和以下代码:

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. 因此,当页面加载时,您会在Label1中看到st = 1。 If user clicks on the Buttton that sometimes you can see st=0 and sometimes st=1. 如果用户点击Buttton,有时你可以看到st = 0,有时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. 当用户点击Button时执行,这就是st变为零的原因。 This behavior I can reproduce in framework 4.5 only: it does not occur in framework 3.5. 我只能在框架4.5中重现这种行为:它不会出现在框架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. 由于托管(IIS)可以在网站调用之间卸载应用程序域,因此静态数据可能会丢失。

So, you really shouldn't rely on static in web apps. 所以,你真的不应该依赖Web应用程序中的静态。

static values are shared across all instances of a class inside of a single App Domain. 静态值在单个App Domain内的所有类实例之间共享。 If you're using IIS Express, your appdomain may be getting recycled more often than you think it is. 如果您使用的是IIS Express,您的应用程序域可能会比您想象的更频繁地进行回收。

reference this: Lifetime of ASP.NET Static Variable 参考: ASP.NET静态变量的生命周期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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