Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DispatcherTimer Stop not stopping

Tags:

c#

.net

wpf

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();        
    }
like image 733
Corbee Avatar asked Oct 31 '25 19:10

Corbee


1 Answers

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(); 
} 
like image 170
Heinzi Avatar answered Nov 03 '25 10:11

Heinzi