This post will discuss how to add a delay to a program in C#.

1. Using Thread.Sleep() method

In C#, the Thread.Sleep() method is commonly used to suspend the current thread execution for a specified amount of time. The following code example demonstrates how to use Thread.Sleep to sleep a console application for 2 seconds.

Download  Run Code

 
Note that Thread.Sleep will completely lock up the current thread and prevent it from further processing other events. So if used within a single-threaded application (say console application), Thread.Sleep will freeze the entire application instead of just delaying a task.

2. Using Task.Delay() method

A better alternative is to use the Task.Delay() method, from the System.Threading.Tasks namespace, which is an asynchronous alternative of Thread.Sleep. It creates a task that will complete after a time delay, which does not block the current thread from processing other events. The following example illustrates.

Download  Run Code

That’s all about adding a delay to a program in C#.