【问题标题】:Why static variable dies in Asp.Net为什么静态变量在 Asp.Net 中消失
【发布时间】:2015-12-19 10:25:25
【问题描述】:

我们知道静态变量活动直到应用程序活动

例如,我们可以用一个 static int 变量来统计访问者的数量。

private static int numberOfVisitors = 0;
protected void Page_Load(object sender, EventArgs e)
{
    numberOfVisitors++;
}

如果上面的句子是正确的,我们可以定义一个static Timer 并且我们期望Elapsed 事件永远触发。

所以,我写了这个应用程序:

public partial class WebForm1 : System.Web.UI.Page
{
    private static System.Timers.Timer timer = new System.Timers.Timer(100);
    private static int numberOfTicks = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = numberOfTicks.ToString();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        timer.Elapsed += timer_Elapsed;
        timer.Start();
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        numberOfTicks++;

    }
}

单击Button1 后,在几分钟内,Lable1.Text 每毫秒增加一次,但当 15 分钟过去后,此标签仅显示0

为什么以及我可以为永久计时器做什么

【问题讨论】:

  • "我们知道静态变量在应用程序存活之前是存活的。" - 不,只要 AppDomain 保留静态变量。因此,如果创建了一个新的 AppDomain,您将获得新的变量...
  • 当 IIS 回收应用程序池时,静态变量被重置
  • @JonSkeet 那么答案是什么:我能为永久计时器做什么?
  • 不要将 ASP.NET 用于计划任务 - 就这么简单。 ASP.NET 中没有“永远”——您处于一个定期回收的托管应用程序中。如果您真的没有其他选择,可以处理这个问题,但除非绝对必要,否则我会避免它。如果需要,有框架可以帮助您。哦,你的代码不是线程安全的。
  • @MehdiKhademloo 您可以在应用程序启动时初始化计时器,并将中间值保存在其他地方(DB?)。但也许你应该更详细地解释你到底想做什么。

标签: c# asp.net timer static scheduled-tasks


【解决方案1】:

静态变量在应用程序域的生命周期内持续存在。所以两人 会导致你的静态变量“重置”的东西是一个应用程序 域重新启动或使用新类。

由于 asp.net 决定在新类中重新编译您的页面,因此您正在丢失您的 aspx 页面中的静态变量。

看看这个链接Understanding ASP.NET Dynamic Compilation

所以,如果您想在特定时间间隔内执行某些任务,我认为您应该看看这个Running task in background 或者这个似乎是一个更好的主意asp.net long running interval tasks

【讨论】:

    猜你喜欢
    • 2010-09-25
    • 1970-01-01
    • 2013-04-05
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 2010-10-10
    • 1970-01-01
    相关资源
    最近更新 更多