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

Viewed 13967

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

Another easy way to suppress the exception of an awaited task is to pass the task as a single argument to Task.WhenAny:

Creates a task that will complete when any of the supplied tasks have completed.

await Task.WhenAny(Task.Delay(500, token)); // Ignores the exception

One problem of this approach is that it doesn't communicate clearly its intention, so adding a comment is recommended. Another one is that it results in an allocation (because of the params in the signature of Task.WhenAny).

I think it deserves to add a comment about why it works that way.

The doc is actually wrong or written unclear about the TaskCancelledException for Task.Delay method. The Delay method itself never throws that exception. It transfers the task into cancelled state, and what exactly raises the exception is await. It didn't matter here that Task.Delay method is used. It would work the same way with any other cancelled task, this is how cancellation is expected to work. And this actually explains why adding a continuation mysteriously hides the exception. Because it's caused by await.

Curiously, the cancellation exception seems to only be thrown when the cancellation token is on Task.Delay. Put the token on the ContinueWith and no cancel exception is thrown:

Task.Delay(500).ContinueWith(tsk => {
   //code to run after the delay goes here
}, cancellationToken.Token);

You can just chain on yet another .ContinueWith() if you really want to catch any cancellation exception - it'll be passed into there.

Related