If you add ContinueWith()
with an empty action, the exception isn't thrown. The exception is caught and passed to the tsk.Exception
property in the ContinueWith()
. But It saves you from writing a try/catch that uglifies your code.
await Task.Delay(500, cancellationToken.Token).ContinueWith(tsk => { });
UPDATE:
Instead of writing code to handle the exception, a boolean would be much cleaner. This is only preferred when a delay cancel is expected!. One way is to create a helper class (Although I don't like helper classes much)
namespace System.Threading.Tasks
{
public static class TaskDelay
{
public static Task<bool> Wait(TimeSpan timeout, CancellationToken token) =>
Task.Delay(timeout, token).ContinueWith(tsk => tsk.Exception == default);
public static Task<bool> Wait(int timeoutMs, CancellationToken token) =>
Task.Delay(timeoutMs, token).ContinueWith(tsk => tsk.Exception == default);
}
}
For example:
var source = new CancellationTokenSource();
if(!await TaskDelay.Wait(2000, source.Token))
{
// The Delay task was canceled.
}
(don't forget to dispose the source)