c# - 为什么静态变量在 Asp.Net 中消亡

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

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

例如,我们可以使用单个 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

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

最佳答案

Static variables persist for the life of the app domain. So the two things that will cause your static variables to 'reset' is an app domain restart or the use of a new class.

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

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

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

关于c# - 为什么静态变量在 Asp.Net 中消亡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32716925/

相关文章:

与 Net Framework 2.0 兼容的 C# JSON Rest 客户端

c# - 防止在 ASP.NET 中回发时关闭 Bootstrap 模式

Android - 实现自定义计时器/时钟

c - PIC16F883 定时器不工作

c# - 'params' 参数参数中的冗余显式数组创建对于索引器不正确

c# - 为什么我不能只使用 EventHandler<int> 而不是从 EventArgs 派生

c# - 内存映射文件与 RAM 磁盘

c# - 如何将此 javascript 函数放置在外部文件中以供用户控制?

asp.net - 对 asp.net 的语义 Web 支持

Flutter - 计时器无意中暂停