C# 计时器拒绝停止计时

本文关键字:计时器 拒绝 | 更新日期: 2023-09-27 17:57:03

我整天都在为此挠头,这让我很生气,这有什么我不知道的明显问题吗?

这是代码:

private Timer _timer = null;
private EventHandler ev = null;
private void startAnimatingPicStatus()
{
     Console.WriteLine("    | STARTING ANIMATION");
     _timer = new Timer();
     _timer.Interval = 100;
     ev = new EventHandler(timer_Tick);
     _timer.Tick += ev;
     _timer.Start();
 }
 private int animationPosition = 0;
 private void timer_Tick(object sender, EventArgs e)
 {
     Console.WriteLine("    | ANIMATING ANIMATION");
     animationPosition++;
     if (animationPosition == 4) animationPosition = 1;
     Dictionary<int, Image> images = new Dictionary<int, Image>();
     images[1] = myproject.Properties.Resources.animateimage_1;
     images[2] = myproject.Properties.Resources.animateimage_2;
     images[3] = myproject.Properties.Resources.animateimage_3;
     picStatus.Image = images[animationPosition];
 }
 private void stopAnimatingPicStatusIfAnimatingAndSetToComplete()
 {
     Console.WriteLine("    | STOPPING ANIMATION");
     _timer.Tick -= ev;
     _timer.Dispose();
     picStatus.Image = nofolder.Properties.Resources.tfolderg;            
  }

这是我期望的调试:

| STARTING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| STOPPING ANIMATION

但这就是我得到的:

| STARTING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| STOPPING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION
| ANIMATING ANIMATION

好消息是它似乎确实停止了动画。 坏消息是它只是有时,它是随机的,但似乎发生在 50% 的时间 - 50% 的时间动画停止,大约 50% 的时间它只是旋转动画,即使它应该停止

编辑>解决方案 我在startAnimatingPicStatus()里面添加了if (ev != null) _timer.Tick -= ev;,就在说ev = new EventHandler(timer_Tick);的行之前,这似乎已经修复了它

C# 计时器拒绝停止计时

要停止计时器,您是否尝试使用 Change 方法,就像 :

myTimer.Change(Timeout.Infinite, Timeout.Infinite);

更多信息在这里 : https://msdn.microsoft.com/en-us/library/yz1c7148%28v=vs.110%29.aspx