Make a Delay Timer in C#

  1. Use the Sleep() Method to Make a Delay in C
  2. Use the Delay() Method to Make a Delay in C

This article will introduce different methods to add a delay in C#. It includes the Sleep() method and the Delay() method. The C# delay timer is set with the given argument.

Use the Sleep() Method to Make a Delay in C

In C#, we can use the Sleep() method to add a delay. This method has two overloads. We will use the following overload in this case. The correct syntax to use this method is as follows.

Thread.Sleep(int milliseconds);

This overload of the Sleep() method has one parameter only. The detail of its parameter is as follows.

Parameters Description
milliseconds mandatory This is the delay time.

This function causes a delay of the specified milliseconds in C#.

The program below shows how we can use the Sleep() method to have a sleep delay of 2 seconds in C#.

using System;
using System.Threading;

class AddDelay {
  static void Main(string[] args) {
    int mydelay = 2000;
    Console.Write("The delay starts.\n");
    Thread.Sleep(mydelay);
    Console.Write("The delay ends.");
  }
}

Csharp Delay Timer

Use the Delay() Method to Make a Delay in C

In C#, we can also use the Delay() method to introduce a sleep delay. This method has multiple overloads. We will use the following overload in this case. The correct syntax to use this method is as follows.

Task.Delay(int milliseconds);

This overload of method Delay() has one parameter only. The detail of its parameter is as follows.

Parameters Description
milliseconds mandatory This is the delay time.

This function initiates a delay timer with the specified milliseconds in C#.

The program below shows how we can use the Delay() method to add a sleep delay for 2 seconds.

using System;
using System.Threading.Tasks;

class AddDelay {
  static void Main(string[] args) {
    int mydelay = 2000;
    // something before delay
    await Task.Delay(mydelay);
    // something after delay
    }
  }
}
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.