views:

59

answers:

4

I have a TextBox with a TextChanged event wired up. In the end it is making a query to a SQL database, so I want to limit the number of queries. I only want to make the query if the user hasn't pressed a key in say .. 300 milliseconds or so. If for some reason the previous query is still executing, I would need to cancel that, and then issue a new query.

A: 

Add a second actionlistener that gets called whenever the user presses any key and when it gets called save the current time to a global variable. Then whenver your TextChanged event gets called it checks to see the time difference between the global variable and the current time.

If the difference is less than 300 milliseconds then start a timer to execute the query after 300 milliseconds. Then if the user presses another key it resets the timer first.

Kyra
This requires the user to wait 300ms and then type another character if they want to submit results.
Brian
A: 

Use the Reactive Framework to trigger on a sequence of events. I'm not sure exactly how this would work, but you can read up on it here (Reactive Extensions for .NET) and see if it will fulfill your needs. There are a bunch of examples here too: Examples. The "Throttling" example may be what you're looking for.

Garo Yeriazarian
+1  A: 

Create a System.Windows.Forms.Timer and reset it (e.g. stop then start it) after every keypress. If the timer event is triggered, disable the timer.

Brian
This is the method I used and it worked perfectly. Surprisingly I am not getting any exceptions about the UI being updated by another thread?
esac
See http://msdn.microsoft.com/en-us/magazine/cc164015.aspx#S1 . The short answer is that the event is executed in the UI thread. Which makes sense, considering that it is in the `System.Windows.Forms` namespace.
Brian
A: 

1) Create a timer.

2) Create a handler for the Tick event of your timer. On each tick, check to see if enough idle time has elapsed, and if it has, STOP the timer and execute the query.

3) Whenever a keypress occurs on that textbox, RESTART the timer.

seraphym