So I'm basically trying to delay the invocation of filter process by 1.5 seconds to allow user to type multiple keystrokes in case they want to. If a new keystroke is typed, previously waiting task is cancelled and a new one starts waiting:
System.Threading.CancellationTokenSource token = new System.Threading.CancellationTokenSource(); private async void MyTextBox_TextChanged(object sender, TextChangedEventArgs e) { token.Cancel(); await System.Threading.Tasks.Task.Delay(1500, token.Token); this.filterText = (sender as TextBox).Text; (this.Resources["CVS"] as CollectionViewSource).View.Refresh(); //Earlier I had tried this variant too: //System.Threading.Tasks.Task.Delay(500, token.Token).ContinueWith(_ => //{ // this.filterText = (sender as TextBox).Text; // (this.Resources["CVS"] as CollectionViewSource).View.Refresh(); //}); } But the filter process (View.Refresh() line) hits immediately on first keystroke without waiting. My impression was that calling Cancel on the token would kill Delay() and thereby the continuation task too, before planting the next one, but apparently this scheme doesn't work.
What am I missing?
token.Token<- you confuse yourself.tokenis not a token, it's aCancellationTokenSource. use proper naming, so it's clear what it is and what it does. And note, doesCancellationTokenSourcehave aReset()orUnCancel()method? No. You need a new one. Edit: I just see it has aTryReset. Still, might not be the best use-case.