Search code examples
c#wpfmultithreadingc#-4.0dispatcher

WPF: how to invoke a method in a separate thread with a delay time


I have a TextBox that user can enter search-term in it. Its bind to string Term property in my view-model. And I want to do a search query when its content changed. But I want to do the query in a separate thread with a delay.

e.g. when user type a letter, I want to wait for 0.3 second, and if user change the input within this time (0.3 second), the timer resets and starts again. Otherwise, I start a new thread and do the search query. While query is executing, if user change the term again, abort prev query and start again.

I know how to do this in windows-forms with threading and Timer class. But I'm new to WPF and I'm searching if there is a way specified for WPF threading functionality (or may be a way with a better performance).

Have you any idea? Can you help me?


Solution

  • You could use DispatcherTimer. On each keypress, stop the timer if it's already running, then start it. I believe (and you should check this!) that that will reset it.

    If it fires, you then take the current value in the textbox and start performing the operation in a separate thread (e.g. using Task.Factory.StartNew, if you're using .NET 4, or BackgroundWorker, or just creating a new thread).

    Basically that separates the "new thread" part from the "do I really want to do something" part, keeping everything on the UI thread until the point where you've decided you really do want to do something (and you know the value you want to use).