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

Andrew Roberts picture Andrew Roberts · Dec 11, 2013 · Viewed 10k times · Source

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();
    }
}

Answer

Jeroen van Langen picture Jeroen van Langen · Sep 24, 2015

If you add ContinueWith() with an empty action, the exception isn't thrown. The exception is caught and passed to the task.Exception property in the ContinueWith(). But It saves you from writing a try/catch that's uglify your code.

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