Don't raise TextChanged while continuous typing
I've come across this problem several times, and based on my own experience I found this solution simple and neat so far. It is based on Windows Form
but can be converted to WPF
easily.
How it works:
When TypeAssistant
learns that a text change
has happened, it runs a timer. After WaitingMilliSeconds
the timer raises Idle
event. By handling this event, you can do whatever job you wish (such as processing the entered tex). If another text change
occurs in the time frame starting from the time that the timer starts and WaitingMilliSeconds
later, the timer resets.
public class TypeAssistant
{
public event EventHandler Idled = delegate { };
public int WaitingMilliSeconds { get; set; }
System.Threading.Timer waitingTimer;
public TypeAssistant(int waitingMilliSeconds = 600)
{
WaitingMilliSeconds = waitingMilliSeconds;
waitingTimer = new Timer(p =>
{
Idled(this, EventArgs.Empty);
});
}
public void TextChanged()
{
waitingTimer.Change(WaitingMilliSeconds, System.Threading.Timeout.Infinite);
}
}
Usage:
public partial class Form1 : Form
{
TypeAssistant assistant;
public Form1()
{
InitializeComponent();
assistant = new TypeAssistant();
assistant.Idled += assistant_Idled;
}
void assistant_Idled(object sender, EventArgs e)
{
this.Invoke(
new MethodInvoker(() =>
{
// do your job here
}));
}
private void yourFastReactingTextBox_TextChanged(object sender, EventArgs e)
{
assistant.TextChanged();
}
}
Advantages:
- Simple!
- Working in
WPF
andWindows Form
- Working with .Net Framework 3.5+
Disadvantages:
- Runs one more thread
- Needs Invocation instead of direct manipulation of form
I also think that the Reactive Extensions are the way to go here. I have a slightly different query though.
My code looks like this:
IDisposable subscription =
Observable
.FromEventPattern(
h => textBox1.TextChanged += h,
h => textBox1.TextChanged -= h)
.Select(x => textBox1.Text)
.Throttle(TimeSpan.FromMilliseconds(300))
.Select(x => Observable.Start(() => /* Do processing */))
.Switch()
.ObserveOn(this)
.Subscribe(x => textBox2.Text = x);
Now this works precisely the way you were anticipating.
The FromEventPattern
translates the TextChanged
into an observable that returns the sender and event args. Select
then changes them to the actual text in the TextBox
. Throttle
basically ignores previous keystrokes if a new one occurs within the 300
milliseconds - so that only the last keystroke pressed within the rolling 300
millisecond window are passed on. The Select
then calls the processing.
Now, here's the magic. The Switch
does something special. Since the select returned an observable we have, before the Switch
, an IObservable<IObservable<string>>
. The Switch
takes only the latest produced observable and produces the values from it. This is crucially important. It means that if the user types a keystroke while existing processing is running it will ignore that result when it comes and will only ever report the result of the latest run processing.
Finally there's a ObserveOn
to return the execution to the UI thread, and then there's the Subscribe
to actually handle the result - and in my case update the text on a second TextBox
.
I think that this code is incredibly neat and very powerful. You can get Rx by using Nuget for "Rx-WinForms".
One easy way is to use async/await on an inner method or delegate:
private async void textBox1_TextChanged(object sender, EventArgs e) {
// this inner method checks if user is still typing
async Task<bool> UserKeepsTyping() {
string txt = textBox1.Text; // remember text
await Task.Delay(500); // wait some
return txt != textBox1.Text; // return that text chaged or not
}
if (await UserKeepsTyping()) return;
// user is done typing, do your stuff
}
No threading involved here. For C# version older than 7.0, you can declare a delegate:
Func<Task<bool>> UserKeepsTyping = async delegate () {...}
Please note, that this method will not secure you from occasionally processing the same "end reslut" twice. E.g. when user types "ab", and then immediately deletes "b", you might end up processing "a" twice. But these occasions shoud be rare enough. To avoid them, the code could be like this:
// last processed text
string lastProcessed;
private async void textBox1_TextChanged(object sender, EventArgs e) {
// clear last processed text if user deleted all text
if (string.IsNullOrEmpty(textBox1.Text)) lastProcessed = null;
// this inner method checks if user is still typing
async Task<bool> UserKeepsTyping() {
string txt = textBox1.Text; // remember text
await Task.Delay(500); // wait some
return txt != textBox1.Text; // return that text chaged or not
}
if (await UserKeepsTyping() || textBox1.Text == lastProcessed) return;
// save the text you process, and do your stuff
lastProcessed = textBox1.Text;
}