2012-11-16 19 views
12

我在我的代碼中有一個Windows.Forms.Timer,我正在執行3次。但是,定時器根本不調用滴答功能。定時器不會打勾

private int count = 3; 
private timer; 
void Loopy(int times) 
{ 
    count = times; 
    timer = new Timer(); 
    timer.Interval = 1000; 
    timer.Tick += new EventHandler(timer_Tick); 
    timer.Start(); 
} 

void timer_Tick(object sender, EventArgs e) 
{ 
    count--; 
    if (count == 0) timer.Stop(); 
    else 
    { 
     // Do something here 
    } 
} 

Loopy()正在代碼中的其他地方被調用。

+1

第一個答案是正確:) –

+1

從正在打電話糊塗? – Adil

+0

Loopy()從代碼中的另一個地方被調用。 – cpdt

回答

35

使用try System.Timers代替Windows.Forms.Timer

void Loopy(int times) 
{ 
    count = times; 
    timer = new Timer(1000); 
    timer.Enabled = true; 
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); 
    timer.Start(); 
} 

void timer_Elapsed(object sender, ElapsedEventArgs e) 
{ 
    throw new NotImplementedException(); 
} 
+0

+1是迄今唯一有用的答案。 – avishayp

+0

太棒了!有用!不知道爲什麼...... – cpdt

+2

我真的不清楚這可以解決這個問題。行爲完全一樣(但是我再也不能重現原來的問題了)。 – jeroenh

2

我不確定你在做什麼錯,它看起來是正確的,這段代碼的作品:看看它是如何比較你的。

public partial class Form1 : Form 
{ 
    private int count = 3; 
    private Timer timer; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     Loopy(count); 
    } 

    void Loopy(int times) 
    { 
     count = times; 
     timer = new Timer(); 
     timer.Interval = 1000; 
     timer.Tick += new EventHandler(timer_Tick); 
     timer.Start(); 
    } 

    void timer_Tick(object sender, EventArgs e) 
    { 
     count--; 
     if (count == 0) timer.Stop(); 
     else 
     { 
      // 
     } 
    } 

} 
2

這裏是一個Rx股票的作品:

Observable.Interval(TimeSpan.FromSeconds(1)) 
.Take(3) 
.Subscribe(x=>Console.WriteLine("tick")); 

當然,你可以訂閱一些更有益你的程序。

+1

真的這是最好的答案。任何時候,當我看到顯式添加或刪除事件處理程序時,我都會查找預先烘焙的RX解決方案,或者編寫一個擴展方法來包裝事件處理。請注意,Take(3)不僅可以處理三個樣本,還可以處理事件處理程序,因此不會泄漏內存。上述所有解決方案在獲取事件後都忘記刪除事件處理程序。 – bradgonesurfing

3

如果方法Loopy()在不是主UI線程的線程中調用,那麼定時器不會打勾。 如果您想從代碼中的任何位置調用此方法,則需要檢查InvokeRequired屬性。所以,你的代碼應該看起來像(假設代碼是一種形式):

 private void Loopy(int times) 
     { 
      if (this.InvokeRequired) 
      { 
       this.Invoke((MethodInvoker)delegate 
       { 
        Loopy(times); 
       }); 
      } 
      else 
      { 
       count = times; 
       timer = new Timer(); 
       timer.Interval = 1000; 
       timer.Tick += new EventHandler(timer_Tick); 
       timer.Start(); 
      } 
     }