Skip to main content

How to Wait Without Blocking with Task.Delay in C#

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

Retrying after a short pause, waiting before the next poll, showing a message for a few seconds: programs often need to wait. In C#, await Task.Delay(...) waits for the time you give it without blocking a thread, and a cancellation token can end the wait early.

Syntax​

Syntax
await Task.Delay(<delay>);
await Task.Delay(<delay>, <cancellationToken>);
PartWhat it does
<delay>How long to wait: a TimeSpan, such as TimeSpan.FromSeconds(2), or a number of milliseconds.
<cancellationToken>Optional. When it's cancelled, the wait ends early and await throws TaskCanceledException.
awaitWaits for the delay to finish before the next line runs.

Microsoft's Task.Delay reference: "Creates a task that completes after a specified time interval." For the version with a token: "If the cancellation token is signaled before the specified time delay, a TaskCanceledException exception results, and the task is completed in the Canceled state."

The Example​

The example prints a line, waits 2 seconds and prints another. Then it starts a 10-second wait with a token that cancels itself after 1 second, and catches the cancellation.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which prints Waiting 2 seconds..., awaits Task.Delay for 2 seconds and prints Done., then awaits a 10-second Task.Delay with a CancellationTokenSource that cancels after 1 second and prints Cancelled after 1 second. when TaskCanceledException is caught.

main.cs
Console.WriteLine("Waiting 2 seconds...");
await Task.Delay(TimeSpan.FromSeconds(2));
Console.WriteLine("Done.");

var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(1));
try
{
await Task.Delay(TimeSpan.FromSeconds(10), cancellation.Token);
}
catch (TaskCanceledException)
{
Console.WriteLine("Cancelled after 1 second.");
}

new CancellationTokenSource(TimeSpan.FromSeconds(1)) creates a token that cancels itself one second later. Its reference: "Initializes a new instance of the CancellationTokenSource class that will be canceled after the specified time span." Passing cancellation.Token to Task.Delay lets that cancellation end the 10-second wait.

Step 2: Run It​

Terminal
dotnet run main.cs
Output
Waiting 2 seconds...
Done.
Cancelled after 1 second.

A zsh terminal where dotnet run main.cs prints Waiting 2 seconds..., Done. and Cancelled after 1 second.

Done. appeared 2 seconds after the first line. The second wait asked for 10 seconds, but the token cancelled it after 1, so await threw TaskCanceledException and the catch printed the last line. The command is the same in zsh, bash and PowerShell.

What Happens Without await​

Task.Delay only creates a task that finishes later; await is what waits for it. Without await:

main.cs
Console.WriteLine("Waiting 2 seconds...");
Task.Delay(TimeSpan.FromSeconds(2));
Console.WriteLine("Done.");
Output
/Users/you/demo/main.cs(2,1): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
Waiting 2 seconds...
Done.

The whole run took 0.59 seconds, measured with time, against 2.54 seconds with await: nothing waited. The CS4014 warning points at the line.

Common Mistakes​

MistakeWhat happensDo this instead
Calling Task.Delay(...) without awaitwarning CS4014, and the code doesn't wait at allWrite await Task.Delay(...)
Passing a token and not catching the cancellationTaskCanceledException ends the program when the token is cancelledCatch TaskCanceledException, or OperationCanceledException, which it derives from
Using Thread.Sleep in asynchronous codeThe thread is blocked and can't do other work while it waitsUse await Task.Delay

Troubleshooting​

SymptomLikely causeFix
No pause at allawait is missingAdd await
CS4014 on a Task.Delay lineThe returned task isn't awaitedAdd await
An unhandled TaskCanceledExceptionThe token was cancelled during the delayCatch it where cancelling is expected

FAQ​

Task.Delay or Thread.Sleep?​

Thread.Sleep blocks the current thread: it can do nothing else until the time is up. await Task.Delay gives the thread back while it waits and continues your code afterwards. In asynchronous code, use Task.Delay.

How do I cancel a wait from somewhere else?​

Keep the CancellationTokenSource and call its Cancel() method when the wait should stop. Every Task.Delay that received its token then ends with TaskCanceledException.

Conclusion​

await Task.Delay(TimeSpan.FromSeconds(2)); waits two seconds without blocking a thread. Pass a cancellation token to end the wait early, catch TaskCanceledException where you expect that, and never leave out the await.

Additional Resources​