Search code examples
c#wpfdispatchertimer

How to call a method if event got not fired again


I wanna call a method in a TextChanged event only if the event got not fired again within one second.

How can this be done in WPF (maybe using a DispatcherTimer)?

I currently use this code but it does not call MyAction() within Method:

bool textchanged = false;

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    textchanged = true;
    DispatcherTimer dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += (o, s) => { Method(); };
    dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
    dispatcherTimer.Start();
}

void Method()
{
    if (!textchanged) //here always false
    {
        //never goes here
        MyAction();
    }
    //always goes here
}

Solution

  • Change your code to the following:

    DispatcherTimer dispatcherTimer = new DispatcherTimer();
    
    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (dispatcherTimer.IsEnabled)
        {
            dispatcherTimer.Stop();
        }
        dispatcherTimer.Start();
    }
    
    void Method()
    {
        dispatcherTimer.Stop();
        MyAction();
    }
    

    And add this straight after your InitializeComponent(); line within your constructor:

    dispatcherTimer.Tick += (o, s) => { Method(); };
    dispatcherTimer.Interval = TimeSpan.FromSeconds(1);