2015-01-16 64 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