Reputation: 1009
Update: I put the complete code for reference
I'm trying to use Dispatcher method instead of Forms.Timer()
I have stop at the end of the method, but it kept looping multiple times before stopping. What went wrong?
By the way, I have to mention that I do use a MessageBox.Show() inside the timer if statement. Don't know if this is the cause or not.
private DispatcherTimer mytimer = new DispatcherTimer();
public MainWindow()
{
InitializeComponent();
}
void mytimer_Tick(object sender, EventArgs e)
{
if (mytimer.Interval == new TimeSpan(0,0,2))
{
mytimer.Stop();
if (textBox1.Text.Length <= 1)
{
MessageBox.Show("0");
mytimer.Stop();
}
else
{
//do code
MessageBox.Show("more than 0");
mytimer.Stop();
}
}
}
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
mytimer.Interval = new TimeSpan(0, 0, 2);
mytimer.Tick += new EventHandler(mytimer_Tick);
mytimer.Start();
}
Upvotes: 3
Views: 7548
Reputation: 172200
Every time the text is changed, you add the event handler again. So, if 5 characters are typed, mytimer_Tick
will be called 5 times.
To fix this, assign the event handler only once, for example, in the Window constructor:
public Window1()
{
InitializeComponent();
mytimer.Interval = new TimeSpan(0,0,2);
mytimer.Tick += new EventHandler(mytimer_Tick);
}
private void txtInput_TextChanged(object sender, EventArgs e)
{
mytimer.Start();
}
Upvotes: 7