How Can I Implement A 2 Or 3 Second Delay Using C#?

In C#, you can add a delay using the Thread.Sleep method or the Task.Delay method from the Task Parallel Library (TPL). Here’s an example of how you can add a delay for 2 or 3 seconds using both methods:

Using Thread.Sleep:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Console.WriteLine("Before delay");

        // Add a 2-second delay
        Thread.Sleep(2000);

        Console.WriteLine("After 2-second delay");

        // Add a 3-second delay
        Thread.Sleep(3000);

        Console.WriteLine("After 3-second delay");
    }
}

Using Task.Delay:

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Before delay");

        // Add a 2-second delay
        await Task.Delay(2000);

        Console.WriteLine("After 2-second delay");

        // Add a 3-second delay
        await Task.Delay(3000);

        Console.WriteLine("After 3-second delay");
    }
}

Both methods will pause the execution of the program for the specified duration before continuing with the next line of code.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!