TaskCanceledException when calling Task.Delay with a CancellationToken in an keyboard event

asynchronous, c#, cancellation-token, cancellationtokensource, windows-runtime

Solution

That's to be expected. When you cancel the old `Delay`, it will raise an exception; that's how cancellation works. You can put a simple `try`/`catch` around the `Delay` to catch the expected exception.

Note that if you want to do time-based logic like this, Rx is a more natural fit than `async`.

Problem

I am trying to delay the processing of a method (SubmitQuery() in the example) called from an keyboard event in WinRT until there has been no further events for a time period (500ms in this case). I only want SubmitQuery() to run when I think the user has finished typing. Using the code below, I keep getting a System.Threading.Tasks.TaskCanceledException when Task.Delay(500, cancellationToken.Token); is called. What am I doing wrong here please? ``` CancellationTokenSource cancellationToken = new CancellationTokenSource(); private async void SearchBox_QueryChanged(SearchBox sender, SearchBoxQueryChangedEventArgs args) { cancellationToken.Cancel(); cancellationToken = new CancellationTokenSource(); await Task.Delay(500, cancellationToken.Token); if (!cancellationToken.IsCancellationRequested) { await ViewModel.SubmitQuery(); } } ```

Original source

Related problems