[英]Stop Timer Elapsed event on button click
Here is my Code for calling an event after 1 minute, I have two button one for start and calling elapsed event after every 1 minute and second button for stopping this timer elapsed event to fire. 这是我的代码,用于在1分钟后调用事件,我有两个按钮用于启动并在每1分钟后调用经过的事件,还有第二个按钮用于停止触发此计时器经过的事件。
start Button evnt code is 开始按钮的EVNT代码是
protected void Button1_Click(object sender, EventArgs e)
{
System.Timers.Timer _timer;
_timer = new System.Timers.Timer(10000);
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
}
Timer Elapsed event 计时器已用事件
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
//It works fine it fires after every minute
}
Stop button event code 停止按钮事件代码
protected void Button2_Click(object sender, EventArgs e)
{
//What to do here??
}
I want to stop this timer activity to stop on this button click evnent. 我想停止此计时器活动,以停止在此按钮上单击“ evnent”。 what should be code here??
这里应该是什么代码?
My entire code is 我的整个代码是
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);
//_timer = ;
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;
}
}
Solution 1: you can Call Stop()
method of the Timer
. 解决方案1:您可以调用
Timer
Stop()
方法。
_timer.Stop();
Solution 2: you can Set Enabled
property of the Timer
to false
. 解决方案2:您可以将
Timer
Enabled
属性设置为false
。
_timer.Enabled=false;
Note: I would suggest calling Stop()
method. 注意:我建议调用
Stop()
方法。
Solution 3: 解决方案3:
you are getting Object reference not set to an instance of an object
exception because you have not initialised your timer by clicking on button1
. 您得到的
Object reference not set to an instance of an object
异常Object reference not set to an instance of an object
因为尚未通过单击button1
初始化计时器。 so you should not click on button2
untill unless you click on button1
as button1
click event handler contains initialisation code to make your present code to work. 因此除非您单击
button1
,否则您不应该单击button2
,因为button1
click事件处理程序包含初始化代码以使您的当前代码正常工作。
OR 要么
I would suggest you to move the timer
initialisation statement to outside the Button1
click event handler. 我建议您将
timer
初始化语句移至Button1
click事件处理程序之外。
Try This : 尝试这个 :
System.Timers.Timer _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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.