System.Threading.Timer 定制Web服务器定时器执行事务!

原来在使用System.Threading.Timer的时候碰到一些问题,定时器在运行一段时间后,自动停止!原来是System.Threading.Timer运行一阵子后,IIS线程池开始垃圾回收的时候,timer被回收,
timer中的各项被Dispose。所以,定时器就实效了!

解决的方法是在Global中,定义System.Threading.Timer为全局变量,不是在方法中!在方法中定义就会被IIS线程池回收!

演示一个简单的例子:Application["A"]全局变量每一秒加1,只要IIS不停止网站,全局变量就会一直增加! 

Global.aspx 代码:

    public class Global : System.Web.HttpApplication
    {
        public static System.Threading.Timer stateTimer = null;
       
        protected void Application_Start(object sender, EventArgs e)
        {
            Application["A"] = "0";
            System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false);
            System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(timerCall);
            stateTimer = new System.Threading.Timer(timerDelegate, autoEvent, 0, 1000);                       
        }

        private void timerCall(object arts)
        {
            Application["A"] = (int.Parse(Application["A"].ToString()) + 1).ToString();
        }
     }

MSDN资料:

语法
 
C#
public Timer(
 TimerCallback callback,
 Object state,
 int dueTime,
 int period


参数
callback
类型:System.Threading.TimerCallback

一个 TimerCallback 委托,表示要执行的方法。

state
类型:System.Object

一个包含回调方法要使用的信息的对象,或者为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing)。

dueTime
类型:System.Int32

调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 可防止启动计时器。指定零 (0) 可立即启动计时器。

period
类型:System.Int32

调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值