您的位置:首页 > 其它

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

2015-07-08 21:24 337 查看

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 可以禁用定期终止。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: