What is the usage of Thread.Sleep in C#?

In C#, the Thread.Sleep method is used to pause the execution of the current thread for a certain amount of time. It takes an integer parameter that represents the number of milliseconds to pause. Calling Thread.Sleep will cause the current thread to sleep for the specified time before resuming execution.

For example, the following code demonstrates how to use the Thread.Sleep method in C# to pause the current thread for 2 seconds:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Console.WriteLine("开始执行");
        
        // 暂停当前线程2秒钟
        Thread.Sleep(2000);
        
        Console.WriteLine("执行完毕");
    }
}

In the code above, the program will pause for 2 seconds when it reaches the Thread.Sleep method, and then continue executing the remaining code. This method can be used to simulate delays or to wait before performing certain operations. It is important to note that the Thread.Sleep method will block the current thread, so using it in the UI thread may cause the interface to become unresponsive. Therefore, use it cautiously.

bannerAds