在C#中, Sleep()方法在指定的毫秒数内暂时挂起线程的当前执行,以便其他线程可以有机会开始执行,或者可以获取CPU来执行。 Thread.Sleep
方法的重载列表中有两种方法,如下所示:
- 睡眠(Int32)
- 睡眠时间
睡眠(Int32)
此方法将当前线程挂起描述符的毫秒数。如果超时值为负且不等于无限,则此方法将引发ArgumentOutOfRangeException。
句法:
public static void Sleep (int millisecondsTimeout);
在这里, millisecondsTimeout是线程被挂起的毫秒数。如果millisecondsTimeout参数的值为零,则该线程将其时间片的其余部分放弃给任何可以运行的具有相同优先级的线程。如果没有其他优先级相同的线程可以运行,那么当前线程的执行不会被挂起。
例子:
// C# program to illustrate the
// concept of Sleep(Int32) method
using System;
using System.Threading;
class ExampleofThread {
// Non-Static method
public void thread1()
{
for (int x = 0; x < 2; x++) {
Console.WriteLine("Thread1 is working");
// Sleep for 4 seconds
// Using Sleep() method
Thread.Sleep(4000);
}
}
// Non-Static method
public void thread2()
{
for (int x = 0; x < 2; x++) {
Console.WriteLine("Thread2 is working");
}
}
}
// Driver Class
public class ThreadExample {
// Main method
public static void Main()
{
// Creating instance for mythread() method
ExampleofThread obj = new ExampleofThread();
// Creating and initializing threads
Thread thr1 = new Thread(new ThreadStart(obj.thread1));
Thread thr2 = new Thread(new ThreadStart(obj.thread2));
thr1.Start();
thr2.Start();
}
}
输出:
Thread1 is working
Thread2 is working
Thread2 is working
Thread1 is working
说明:通过使用Thread.Sleep(4000);
在thread1方法中,我们使thr1线程休眠4秒钟,因此thr2线程在4秒钟之间有机会在thr1线程恢复工作4秒钟后执行。
睡眠时间
此方法在描述的时间量内暂停当前线程。如果超时值为负且不等于以毫秒为单位的无限值或大于MaxValue毫秒,则此方法将引发ArgumentOutOfRangeException。
句法 :
public static void Sleep (TimeSpan timeout);
在这里,超时是线程被挂起的时间。如果millisecondsTimeout参数的值为零,则该线程将其时间片的剩余部分放弃给任何优先级相同且可以运行的线程。如果没有其他优先级相同的线程可以运行,那么当前线程的执行不会被挂起。
例子:
// C# program to illustrate the
// concept of Sleep(TimeSpan)
using System;
using System.Threading;
class GFG {
// Main method
static void Main()
{
// Set the timeout value, i.e. 3 seconds
TimeSpan timeout = new TimeSpan(0, 0, 3);
for (int k = 0; k < 3; k++) {
Console.WriteLine("Thread is" +
" sleeping for 3 seconds.");
// Using Sleep(TimeSpan) method
Thread.Sleep(timeout);
}
Console.WriteLine("Main thread exits");
}
}
输出:
Thread is sleeping for 3 seconds.
Thread is sleeping for 3 seconds.
Thread is sleeping for 3 seconds.
Main thread exits
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.sleep?view=netframework-4.7.2