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 代码:
MSDN资料:
语法
C#
public Timer(
)
参数
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 可以禁用定期终止。