I have a textbox that has a fairly hefty _TextChanged event handler. Under normal typing condition the performance is okay, but it can noticeably lag when the u
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. 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".