大家好,我曾经使用过计时器类来调用一分钟,这是我的代码
public partial class TimerScheduler : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
}
System.Timers.Timer _timer = new System.Timers.Timer(10000);
protected void Button1_Click(object sender, EventArgs e)
{
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
_timer.Stop();
_timer.Enabled=false;
}
}
但是当我单击开始按钮计时器工作正常并且在每分钟之后它被调用但是当我试图阻止它时它不起作用并且每1分钟后调用_timer_Elapsed事件
答案 0 :(得分:1)
编辑如下代码
public partial class TimerScheduler : System.Web.UI.Page
{
System.Timers.Timer _timer = new System.Timers.Timer(10000);
protected void Page_Load(object sender, EventArgs e)
{
_timer.Elapsed -= new ElapsedEventHandler(_timer_Elapsed); //to avoid multiple linking of event
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
}
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
_timer.Enabled = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
_timer.Enabled=false;
}
}
答案 1 :(得分:0)
您只需订阅ElapsedEvent
事件处理程序之外的Button1_Click
,然后在Timer
事件处理程序中启动Button1_Click
。
System.Timers.Timer _timer = new System.Timers.Timer(10000);
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
protected void Button1_Click(object sender, EventArgs e)
{
_timer.Start();
}
protected void Button2_Click(object sender, EventArgs e)
{
_timer.Stop();
}
答案 2 :(得分:0)
您可以通过设置AutoReset = false
轻松使定时器点火一次。然后你必须在计时器的事件处理程序中手动重启计时器。
System.Timers.Timer _timer = new System.Timers.Timer(1000);
bool timerStarted = false;
protected void Button1_Click(object sender, EventArgs e)
{
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
_timer.AutoReset = false;
timerStarted = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
timerStarted = false;
_timer.Enabled=false;
}
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_timer.Enabled = timerStarted;
}
哦,顺便说一句:我不知道你想要实现什么,但是ASP.NET页面不运行时间更长的东西。代码在服务器上执行一次,HTML将传递回客户端。所以你想要的东西可能根本不起作用。