2015-01-16 41 views
0

是我第一次使用定时器,所以可能我做错了什么。定时器不工作

我的代码是这样的:

private void timer1_Tick(object sender, EventArgs e) 
    { 
     button2.PerformClick(); 
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 

     // random code here 
      timer1.Interval = 5000; 
      timer1.Start(); 
      timer1_Tick(null,null); 

    } 

我想这是做:执行任意代码,然后等待计时器的时间间隔和执行周期(即会做一个“点击”在再次按钮,再次执行相同的操作),然后重复此操作。

对不起,如果是一个容易的错误,我从这开始,不知道我做错了什么。

谢谢您的阅读! :D

+2

好吧.. http://meta.stackexchange.com/questions/10647/writing-a-good-title –

+2

究竟是什么不起作用?这段代码似乎有一个无限循环。 –

回答

2

定时器事件(针对每种定时器)不需要由您手动调用。

您设置了它的事件处理程序方法,设置间隔并启动它。
底层框架在需要调用时调用Tick事件。

所以你需要把你的随机码放在你可以从Tick事件和你的按钮点击事件调用的子集中。此外,您应该考虑阻止计时器的进一步激活。您可以禁用该按钮,并且当您完成随机代码且条件成立时,停止计时器并重新启用该按钮。

private void button2_Click(object sender, EventArgs e) 
{ 
    stopTheTimer = false; 
    YourCommonMethod(); 
    button2.Enabled = false; 
    timer1.Tick += timer1_Tick 
    timer1.Interval = 5000; 
    timer1.Start(); 
} 

private void timer1_Tick(object sender, EventArgs e) 
{ 
    YourCommonMethod(); 
} 
private void YourCommonMethod() 
{ 
    // execute your 'random' code here 
    if(stopTheTimer) 
    { 
     timer1.Stop(); 
     timer1.Tick -= timer1_Tick; // disconnect the event handler 
     button2.Enabled = true; 
    } 
} 
+0

请看@Idle_Mind的答案,因为他提出了一个很好的观点。我已经调整了我的答案以反映其观察结果。 – Steve

1

下面是你去。 。 。 。

private void button2_Click(object sender, EventArgs e) 
    { 
     // random code here 
     timer1.Interval = 5000; 
     timer1.Start(); 
     timer1.Tick += timer1_Tick; 

    } 

    void timer1_Tick(object sender, EventArgs e) 
    { 
     //Your timing code here. 
    } 
1

线了蜱()事件仅一次,最好的直通IDE所以你不要有多个处理器和运行不止一次每个蜱()事件的详细代码结束。

*在下面,我有线它在构造函数作为替代......但不这样做线它直通的IDE或将火两次,每次蜱()的示例。

你可能只是想调用start()方法的按钮处理程序,然后在蜱打电话给你的“随机码”()事件是这样的:

public partial class Form1 : Form 
{ 

    public Form1() 
    { 
     InitializeComponent(); 
     timer1.Enabled = false; 
     timer1.Interval = (int)TimeSpan.FromSeconds(5).TotalMilliseconds; 
     timer1.Tick += timer1_Tick; // just wire it up once! 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     if (!timer1.Enabled) 
     { 
      Foo(); // <-- Optional if you want Foo() to run immediately without waiting for the first Tick() event 
      timer1.Start(); 
     } 
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     timer1.Stop(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     Foo(); 
    } 

    private void Foo() 
    { 
     Console.WriteLine("Random Code @ " + DateTime.Now.ToString()); 
    } 

} 

这并不比多大区别其他的答案,但多次连接Tick()事件是一个严重的缺陷...

+0

你是绝对正确的。 Tick事件应该在Form_Load事件中或在设计器中断开或关联一次。我改变了我的答案以反映你的观察。 (和upvoted你的) – Steve