2

我想在另一个线程中更改计时器间隔:

    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());
       }
    }

但是当我更改新线程中的间隔时,计时器会停止。没有错误,计时器只是停止。为什么会发生这种情况,我该如何解决?

谢谢

4

2 回答 2

1

试试这个,我试过了,它可以工作,我只将新的间隔从 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());
    }
于 2012-10-10T20:36:11.153 回答
0

In addition to my previous answer, since you are not using Forms, try to change your System.Windows.Forms.Timer to System.Timers.Timer. Note that it has Elapsed Event, not Tick. The following is the code:

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;
    }

Hope this will finally help!

于 2012-10-10T22:00:17.493 回答