C#Timer拒绝停止滴答

时间:2015-06-18 16:14:08

标签: c# multithreading timer

我整天都在这个问题上摸不着头脑,这让我很生气,有什么明显的问题我不知道吗?

以下是代码:

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%的时间它只是旋转动画应该停止了

编辑&gt;解决方案我在if (ev != null) _timer.Tick -= ev;之前的startAnimatingPicStatus()内添加了ev = new EventHandler(timer_Tick);,这似乎已经修复了

1 个答案:

答案 0 :(得分:1)

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

((IMAPFolder)_folder).copyMessages(new Message[] { getMail().getMessage() }, destination);

此处提供更多信息:https://msdn.microsoft.com/en-us/library/yz1c7148%28v=vs.110%29.aspx