'async/await continuing too soon

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?



Solution 1:[1]

If this helps anyone, the following is correctly working for me. My mistake was that I incorrectly assumed that CancellationTokenSource is a signaling device and could be used multiple times. That is apparently not the case:

private System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();
private async void TenantsFilter_TextChanged(object sender, TextChangedEventArgs e)
{
  cts.Cancel();
  cts = new System.Threading.CancellationTokenSource();

  try
  {
    await System.Threading.Tasks.Task.Delay(1500, cts.Token);
    this.filterText = (sender as TextBox).Text;
    (this.Resources["CVS"] as CollectionViewSource).View.Refresh();
  }
  catch(System.Threading.Tasks.TaskCanceledException ee)
  {
  }
}

Posting it here for my own record and just to let others check I'm still not doing anything wrong.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dotNET