自 .NET 2.0 以来,Thread.Suspend()
和 Thread.Resume()
这两个方法已过时。为什么?还有哪些其他选择和示例?
最佳答案
您需要使用 AutoResetEvent EventWaitHandle。
假设你想做这样的事情(注意:不要这样做!):
private Thread myThread;
private void WorkerThread()
{
myThread = Thread.CurrentThread;
while (true)
{
myThread.Suspend();
//Do work.
}
}
public void StartWorking()
{
myThread.Resume();
}
正如其他人所说,这是个坏主意。尽管仅在其自己的线程上使用 Suspend 相对安全,但您永远无法确定是否在线程实际挂起时调用 Resume。所以 Suspend 和 Resume 已经过时了。
相反,您想使用 AutoResetEvent:
private EventWaitHandle wh = new AutoResetEvent();
private void WorkerThread()
{
while(true)
{
wh.WaitOne();
//Do work.
}
}
public void StartWorking()
{
wh.Set();
}
工作线程将等待等待句柄,直到另一个线程调用 StartWorking。它的工作原理与暂停/恢复非常相似,因为 AutoResetEvent 只允许“恢复”一个线程。
关于c# - 暂停和恢复线程的替代方法有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/382173/