TaskCanceledException when calling Task.Delay with a CancellationToken in an keyboard event
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 => { });
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
.
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.