📜  暂停和恢复线程 C# (1)

📅  最后修改于: 2023-12-03 15:26:20.811000             🧑  作者: Mango

暂停和恢复线程 C#

在C#中,可以使用Thread.Sleep方法暂停线程,也可以使用Thread.Interrupt方法中断线程。但是,如果需要暂停一个线程,并随时恢复它,Thread.Sleep和Thread.Interrupt方法是不太适合的。因此,这里介绍一种通过设置线程状态来暂停和恢复线程的方法。

设置线程状态

C#提供了ThreadState枚举来描述线程的不同状态。可以使用Thread.CurrentThread.ThreadState属性获取当前线程的状态。

if(Thread.CurrentThread.ThreadState == ThreadState.Running){
    //线程正在运行
}
else if(Thread.CurrentThread.ThreadState == ThreadState.Suspended){
    //线程已暂停
}

可以使用Thread.Suspend方法暂停线程,使用Thread.Resume方法恢复线程。但是这两个方法已经被标记为过时,不建议使用,因为它们可能会导致线程死锁或其他问题。

用ManualResetEvent暂停和恢复线程

ManualResetEvent是C#中一种同步辅助类,它提供了一个信号状态,等待线程可以阻塞在获取这个信号的地方。可以使用ManualResetEvent来实现暂停和恢复线程。

public class MyThread {
    private ManualResetEvent eventPause = new ManualResetEvent(true);
    private ManualResetEvent eventResume = new ManualResetEvent(false);

    public void ThreadProc() {
        while (true) {
            eventPause.WaitOne();
            //执行线程代码

            eventResume.WaitOne();
        }
    }

    public void Pause() {
        eventPause.Reset();
        eventResume.Set();
    }

    public void Resume() {
        eventPause.Set();
        eventResume.Reset();
    }
}

在上面的示例中,ManualResetEvent eventPause的初始状态为true,表示开始线程执行。ManualResetEvent eventResume的初始状态为false,表示线程暂停。Pause方法会将eventPause置为false,使得线程处于暂停状态,然后将eventResume置为true,以便在Resume方法被调用时恢复线程。Resume方法正好相反,将eventPause置为true,使得线程可以继续执行,然后将eventResume置为false,将线程恢复到暂停状态。

总结

这里介绍了使用ManualResetEvent来暂停和恢复线程的方法,相对于Thread.Suspend和Thread.Resume方法,这种方法更加稳定和安全。通过这种方法,可以很好地控制线程的生命周期,达到更加可靠的程序设计效果。