2012-10-10 34 views
0

計時器的時間間隔,我想在另一個線程更改計時器間隔:改變其他線程

class Context : ApplicationContext { 
     private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); 
     public Context() { 
      timer.Interval = 1; 
      timer.Tick += timer_Tick; 
      timer.Start(); 
      Thread t = new Thread(ChangeTimerTest); 
      t.Start(); 
     } 
     private void ChangeTimerTest() { 
      System.Diagnostics.Debug.WriteLine("thread run"); 
      timer.Interval = 2; 
     } 
     private void timer_Tick(object sender,EventArgs args) { 
      System.Diagnostics.Debug.WriteLine(System.DateTime.Now.ToLongTimeString()); 
     } 
    } 

但是當我改變在新線程的間隔計時器停止。沒有錯誤,計時器停止。 爲什麼會發生這種情況,我該如何解決?

THX

+0

你試過開始和停止它嗎? –

+0

你的代碼根本不是線程安全的。不知道這是否是您看到帽子的直接原因,但最終會導致問題。 –

+0

開始和停止給出相同的結果 –

回答

0

試試這個,我想它和它的作品,我只是改變了新的時間間隔從2到2000毫秒,所以你可以看到在輸出的差異。 因爲定時器在UI線程上下文中,所以必須以線程安全方式更改間隔。在這些情況下,建議使用代表。

private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); 
    public void Context() { 
     timer.Interval = 1; 
     timer.Tick += timer_Tick; 
     timer.Start(); 
     Thread t = new Thread(ChangeTimerTest); 
     t.Start(); 
    } 
    delegate void intervalChanger(); 
    void ChangeInterval() 
    { 
     timer.Interval = 2000; 
    } 
    void IntervalChange() 
    { 
     this.Invoke(new intervalChanger(ChangeInterval)); 
    } 
    private void ChangeTimerTest() { 
     System.Diagnostics.Debug.WriteLine("thread run"); 
     IntervalChange(); 
    } 
    private void timer_Tick(object sender,EventArgs args) { 
     System.Diagnostics.Debug.WriteLine(System.DateTime.Now.ToLongTimeString()); 
    } 
+0

是的。這項工作:)。但我的類不包含方法「invoke」:(。類MainContext:ApplicationContext。我該如何添加此方法? –

+0

那麼,你應該找出如何將你的類的引用傳遞給你的類,也許槽構造函數參數。 myFormReference.Invoke 我不能給你一個完整的答案,因爲我不知道你是如何使用Context類的,但很明顯,定時器在你的UI線程中執行,因此你應該以線程安全的方式更改它 –

+0

有一種解決方法是如何在代碼中隨時隨地獲取表單,但我並不是建議您使用它,當我使用它時,它非常方便,但我不確定它是否完全正常。程序 { public static Form myForm; [STAThread] static void Ma in() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); myForm = new Form1(); Application.Run(myForm); } } –

0

除了我以前的答案,因爲你沒有使用表單,嘗試將System.Windows.Forms.Timer改變System.Timers.Timer。請注意,它已經發生了Elapsed事件,而不是Tick。以下是代碼:

System.Timers.Timer timer = new System.Timers.Timer(); 
    public Context() { 
     timer.Interval = 1; 
     timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); 

     timer.Start(); 
     Thread t = new Thread(ChangeTimerTest); 
     t.Start(); 
    } 

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    { 
     System.Diagnostics.Debug.WriteLine(System.DateTime.Now.ToLongTimeString()); 
    } 

    private void ChangeTimerTest() { 
     System.Diagnostics.Debug.WriteLine("thread run"); 
     timer.Interval = 2000; 
    } 

希望這會最終幫助!