2012-10-10 29 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; 
    } 

希望这会最终帮助!