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

I am trying to postpone the processing of the method (SubmitQuery () in the example) called from a keyboard event in WinRT until there are no events for a period of time (in this case there will be 500 ms).

I want the SubmitQuery () function to run when I think the user has finished typing.

Using the following code, I keep getting System.Threading.Tasks.TaskCanceledException when Task.Delay (500, cancelationToken.Token); 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(); } } 
+13
c # asynchronous windows-runtime cancellationtokensource
source share
2 answers

What to expect. When you cancel the old Delay , it will throw an exception; how cancellation works. You can put a simple try / catch around Delay to catch the expected exception.

Note that if you want to use time logic like this, Rx is more natural than async .

+15
source share

If you add ContinueWith() with an empty action, an exception is not thrown. The exception is caught and passed to task.Exception in ContinueWith()

 await Task.Delay(500, cancellationToken.Token).ContinueWith(tsk => { }); 
+36
source share

All Articles