C# Time Delay After User Input

asynchronous, c#, delay, time, wpf

Solution

You can easily do the using a DispatcherTimer:

public class MyBox : TextBox
{
    private readonly DispatcherTimer timer;

    public MyBox()
    {
        timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
        timer.Tick += OnTimerTick;
    }

    protected override void OnTextChanged(TextChangedEventArgs e)
    {
        timer.Stop();
        timer.Start();
    }

    private void OnTimerTick(object sender, EventArgs e)
    {
        timer.Stop();
        // do something here
    }
}

Problem

I've got a custom control (inheriting from TextBox) that I'm working with in .NET 4.0. What I need to be able to do is execute some code after the user has finished his input, e.g. one second after he stops typing. I can't execute this code block each time the Text changes, for efficiency's sake and because it is somewhat time-consuming. It should ideally only be called once each time the user starts and stops typing. I have begun by using Stopwatch's `Restart()` inside the `OnTextChanged` method. Here's my setup: ``` public class MyBox : TextBox { private readonly Stopwatch timer; protected override void OnTextChanged(TextChangedEventArgs e) { timer.Restart(); base.OnTextChanged(e); } } ``` How can I do this efficiently? Are async threads the answer? Or is there some other way?

Original source