📜  c# Sleep - C# (1)

📅  最后修改于: 2023-12-03 14:59:40.853000             🧑  作者: Mango

C# Sleep

Sleep is a method in C# that allows you to pause the execution of a program for a specified amount of time. It is commonly used in scenarios where you want to introduce a delay in the execution of your code.

Syntax

The syntax of the Sleep method is as follows:

System.Threading.Thread.Sleep(milliseconds);

Here, milliseconds is an integer value representing the number of milliseconds for which you want to pause the program.

Example
using System;
using System.Threading;

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Starting the program.");

        // Pause the program for 3 seconds
        Thread.Sleep(3000);

        Console.WriteLine("Resuming the program.");
    }
}

In the above example, the program will pause for 3 seconds using the Sleep method. After the pause, it will continue with the execution and print "Resuming the program." to the console.

Important Note

The Sleep method is a blocking call, meaning that it will pause the execution of the current thread. This can cause performance issues in some scenarios, especially in GUI applications where the main thread is responsible for handling user input and updating the UI. In such cases, it is recommended to use asynchronous programming techniques or timers instead of Sleep.