Reputation: 23
I'd like to change a timer interval in another thread:
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());
}
}
But the timer stops when I change the interval in the new thread. No errors, timer just stops. Why is this happening and how can I fix it?
thx
Upvotes: 2
Views: 2357
Reputation: 8656
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!
Upvotes: 0
Reputation: 8656
Try this, I tried it and it works, I only changed new interval from 2 to 2000ms so you can see the difference in the Output. You have to change interval in a thread safe manner your interval because the timer is in UI thread context. In these cases it is recommended to use delegates.
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());
}
Upvotes: 1