Add a delay to a program in C#
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Threading; public class Example { public static void Main() { Console.WriteLine("Sleeping for 2 seconds..."); Thread.Sleep(2000); Console.WriteLine("2 seconds elapsed"); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Threading.Tasks; public class Example { public static Task timer = Task.Run(async delegate { await Task.Delay(2000); }); public static void Main() { Console.WriteLine("Sleeping for 2 seconds..."); timer.Wait(); Console.WriteLine("2 seconds elapsed"); } } |
That’s all about adding a delay to a program in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)