ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 为什么静态变量在Asp.Net中死掉

2019-07-06 16:07:04  阅读:243  来源: 互联网

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


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

例如,我们可以使用单个静态int变量计算访问者的数量.

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

如果上面的句子是正确的,我们可以定义一个静态计时器,我们期望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,static,timer,scheduled-tasks
来源: https://codeday.me/bug/20190706/1398701.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有