System.Threading.Timer timer 定时器用上一段时间就会自动停止?
解决办法:
因为需要一直保持对timer的引用,要不然它会被回收。
protected void SendMsg(object sender)
{
System.Threading.Timer timer = new System.Threading.Timer(testTime, this, 0, 60000);
}
像上面这样,定义在方法里的是局部变量,会被回收,需要定义成全局变量。
C#又没有全局变量这一说,
需要定义成静态变量
public class test
{
private static System.Threading.Timer timer;
protected void BtnStart_Click(object sender, EventArgs e)
{
TimerCallback testTime = new TimerCallback(SendMsg);
timer = new System.Threading.Timer(testTime, this, 0, 1000);
}
protected void SendMsg(object sender)
{
//执行代码
}
}