How is the sleep function used in C#?
In C#, the Thread.Sleep() function is used to pause the execution of the current thread for a specified amount of time. It takes an integer parameter that represents the number of milliseconds to pause.
Usage example:
using System;
using System.Threading;
class Program
{
static void Main()
{
Console.WriteLine("开始");
Thread.Sleep(2000); // 暂停当前线程2秒
Console.WriteLine("结束");
}
}
In the above example, the program will first display “start”, then pause for 2 seconds, and finally display “end”.
It is important to note that the Thread.Sleep() function will block the current thread’s execution. If this function is used in the main thread, it will cause the entire application to pause for a period of time. If you need to perform a pause operation in the background, consider using the Task.Delay() function.