Reputation: 91
I am checking the time and when is equal to something I want to stop the dispatcher.
But it doesn't work. Timer is still working after calling Stop()
.
private void startTime(bool what)
{
vartimer = new DispatcherTimer();
if (!what)
{
MessageBox.Show("Start");
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += setTime;
timer.Start();
}
if (what)
{
MessageBox.Show("Stop");
timer.Stop();
}
}
When it starts, it is showing the Start text. When it should stop, it should show the Stop text but it is still working.
Did I do something wrong?
timer.stop();
Should stop the Dispatcher
, right?
Upvotes: 3
Views: 10706
Reputation: 169150
Define the DispacherTimer
outside your method:
DispatcherTimer timer = new DispatcherTimer();
private void startTime(bool what)
{
if (what == false)
{
MessageBox.Show("Start");
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick -= setTime;
timer.Tick += setTime;
timer.Start();
}
if (what == true)
{
MessageBox.Show("Stop");
timer.Stop();
}
}
In your current code, you are creating a new instance of the DispacherTimer
each time the method is called.
Upvotes: 9
Reputation: 3
Class A
{
private DispatcherTimer _timer; // This is a global variable
public void StartTime(bool what)
{
DispatcherTimer timer = new Dispatcher(); //This is a local variable
...
}
}
When you call the StartTime function,the timer is a new instance. If you run StartTime(false) and StartTime(true), it will have two DispatcherTimer;
Upvotes: 0
Reputation: 8382
Your instance of DispatcherTimer
should be a private field of your class because everytime you are calling startTime(...)
, you are creating a new instance of the DispatcherTimer
class that is started but never stopped. Here is an example of what could be done:
public class YourClass : IDisposable
{
private readonly DispatcherTimer m_timer;
public YourClass()
{
m_timer = new DispatcherTimer();
m_timer.Interval = new TimeSpan(0, 0, 1);
m_timer.Tick += setTime;
}
public void Dispose()
{
m_timer.Tick -= setTime;
m_timer.Stop();
}
private void startTime(bool what)
{
if(what == false)
{
MessageBox.Show("Start");
m_timer.Start();
}
if(what == true)
{
MessageBox.Show("Stop");
m_timer.Stop();
}
}
}
I also added the IDisposable
implementation to make sure the Dispatcher
instance is properly unsubscribed from and stopped.
Upvotes: 3