温馨提示×

C#中ManualResetEvent实现线程的暂停与恢复

c#
小云
216
2023-08-08 14:47:15
栏目: 编程语言

在C#中,可以使用ManualResetEvent来实现线程的暂停和恢复。ManualResetEvent是一个同步对象,它包含一个布尔值,表示是否发出信号。当布尔值为true时,表示信号已发出,线程可以继续执行;当布尔值为false时,表示信号未发出,线程需要暂停等待。

下面是一个示例代码,演示了如何使用ManualResetEvent来实现线程的暂停和恢复:

using System; using System.Threading; public class Program { private static ManualResetEvent pauseEvent = new ManualResetEvent(true); // 初始状态为true,线程可以继续执行 public static void Main(string[] args) { Thread thread = new Thread(WorkerThread); thread.Start(); Console.WriteLine("Press any key to pause the thread..."); Console.ReadKey(); PauseThread(); // 暂停线程 Console.WriteLine("Press any key to resume the thread..."); Console.ReadKey(); ResumeThread(); // 恢复线程 Console.WriteLine("Press any key to stop the thread..."); Console.ReadKey(); StopThread(); // 停止线程 } private static void WorkerThread() { while (true) { // 检查是否暂停线程 pauseEvent.WaitOne(); // 执行任务 Console.WriteLine("Working..."); // 模拟耗时操作 Thread.Sleep(1000); } } private static void PauseThread() { pauseEvent.Reset(); // 设置为false,线程将暂停等待 } private static void ResumeThread() { pauseEvent.Set(); // 设置为true,线程将继续执行 } private static void StopThread() { pauseEvent.Set(); // 设置为true,确保线程可以继续执行以结束循环 // 其他处理逻辑... // 终止线程 Environment.Exit(0); } } 

在上面的示例中,程序创建了一个线程(WorkerThread),并在主线程中通过按键的方式来控制线程的暂停和恢复。在WorkerThread中,使用pauseEvent的WaitOne方法来检查是否暂停线程,如果暂停,则线程会处于等待状态,直到调用ResumeThread方法将pauseEvent设置为true,线程才会继续执行。

需要注意的是,使用ManualResetEvent来实现线程的暂停和恢复时,线程不能被阻塞在其他的同步对象(如Mutex、Semaphore等)上,否则可能会出现死锁的情况。

0