使用计时器停止另一个计时器
本文关键字:计时器 另一个 | 更新日期: 2023-09-27 18:26:49
我是C#的业余爱好者,正在做一个项目。
我用了3个计时器,其中一个是20秒的圆形计时器。我希望在20秒后,其他2个计时器必须停止
我无法访问/调用循环计时器中的其他2个计时器。这是代码:
public void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DispatcherTimer tgtTimer = new DispatcherTimer();
tgtTimer.Tick += new EventHandler(tgtTimer_tick);
tgtTimer.Interval = new TimeSpan(0, 0, 3);
tgtTimer.Start();
DispatcherTimer txbTimer2 = new DispatcherTimer();
txbTimer2.Tick += new EventHandler(txbTimer2_tick);
txbTimer2.Interval = new TimeSpan(0, 0, 0, 4, 000);
txbTimer2.Start();
DispatcherTimer rt = new DispatcherTimer();
rt.Tick += new EventHandler(rt_tick);
rt.Interval = new TimeSpan(0, 0, 1);
rt.Start();
}
private void tgtTimer_tick(object sender, EventArgs e)
{ //some code }
private void txbTimer2_tick(object sender, EventArgs e)
{ //some code }
int i = 20 //for the 20 sec round timer
private void rt_tick(object sender, EventArgs e) //round timer
{
if(i!=0)
{
i--;
txbTime.Text = "";
txbTime.Text = Convert.ToString(i) + "s";
}
else
{
this.Opacity = 0.3;
//tgtTimer and txbTimer2 can't be accessed from here
}
}
我应该如何停止2个定时器?
您应该尝试在mouseleftbutton down事件之外添加计时器,如下所示:
DispatcherTimer tgtTimer = new DispatcherTimer();
DispatcherTimer txbTimer2 = new DispatcherTimer();
DispatcherTimer rt = new DispatcherTimer();
public void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
tgtTimer.Tick += new EventHandler(tgtTimer_tick);
tgtTimer.Interval = new TimeSpan(0, 0, 3);
tgtTimer.Start();
txbTimer2.Tick += new EventHandler(txbTimer2_tick);
txbTimer2.Interval = new TimeSpan(0, 0, 0, 4, 000);
txbTimer2.Start();
rt.Tick += new EventHandler(rt_tick);
rt.Interval = new TimeSpan(0, 0, 1);
rt.Start();
}
将对计时器的引用移出按钮点击:
DispatcherTimer tgtTimer = new DispatcherTimer();
DispatcherTimer tgtTimer2 = new DispatcherTimer();
public void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DispatcherTimer tgtTimer = new DispatcherTimer(); //here
tgtTimer.Tick += new EventHandler(tgtTimer_tick);
tgtTimer.Interval = new TimeSpan(0, 0, 3);
tgtTimer.Start();
DispatcherTimer txbTimer2 = new DispatcherTimer(); //and here
txbTimer2.Tick += new EventHandler(txbTimer2_tick);
txbTimer2.Interval = new TimeSpan(0, 0, 0, 4, 000);
txbTimer2.Start();
//or inline the method to stay within scope
DispatcherTimer rt = new DispatcherTimer();
rt.Tick += (ob, ev) =>
{
//still in scope
txbTimer2.Start();
};
rt.Interval = new TimeSpan(0, 0, 1);
rt.Start();
}