Wait For X Seconds In C# - Add Delay In C#

Sameer Saini March 30, 2022
Wait For X Seconds In C# - Add Delay In C#

In this blog post, we will learn a couple of ways by which we can wait for X seconds in C# and delay execution.

There can be a few use cases for adding a delay or for waiting for X seconds before you resume execution of your code in C# such as printing records back to the console, adding an explicit delay to mock or stub a slow running server or a backend service, etc.

 

 

 

Wait For X Seconds In C# Using Thread.Sleep() Method - C# Delay Using Thread.Sleep()

The Thread.Sleep() method suspends the current thread for the specified amount of time.

The method takes an integer value that suspends the current thread for the specified number of milliseconds.

public static void Main() { Console.WriteLine("The program has started."); Console.WriteLine("Using Thread.Sleep() To Add A 5 Second Delay."); Console.WriteLine("Time before wait: " + DateTime.Now.ToString()); // Wait for 5 seconds Thread.Sleep(5000); Console.WriteLine("Time after wait: " + DateTime.Now.ToString()); Console.WriteLine("The program has ended."); Console.ReadLine(); }

 

Result:

The program has started. Using Thread.Sleep() To Add A 5 Second Delay. Time before wait: 30/03/2022 1:22:25 PM Time after wait: 30/03/2022 1:22:30 PM The program has ended.

 

From the above example, we can see that we can add a wait of x seconds in C# using the Thread.Sleep() method.

 

 

 

Wait For X Seconds In C# Using Task.Delay() Method - C# Delay Using Task.Delay()

There is another method in C# that we can use to wait for x seconds or to add a delay in execution in C#.

This method is Task.Delay() and it creates a task that will complete after a time delay.

As a parameter, this method takes an integer value of the number of milliseconds to delay.

public class Program { public static void Main() { Task.Run(async delegate { await AddDelayExample(); }).Wait(); } public static async Task AddDelayExample() { Console.WriteLine("The program has started."); Console.WriteLine("Using Thread.Sleep() To Add A 5 Second Delay."); Console.WriteLine("Time before wait: " + DateTime.Now.ToString()); // Wait for 5 seconds await Task.Delay(5000); Console.WriteLine("Time after wait: " + DateTime.Now.ToString()); Console.WriteLine("The program has ended."); Console.ReadLine(); } }

 

Result:

The program has started. Using Thread.Sleep() To Add A 5 Second Delay. Time before wait: 30/03/2022 1:32:53 PM Time after wait: 30/03/2022 1:32:58 PM The program has ended.

In the above example, we used the Task.Delay() method to add a delay in C#. It takes the number of milliseconds you want to add a delay for.

This is used inside an async method and we used the await keyword as Task.Delay is an async method.