gpt4 book ai didi

c# - 暂停和恢复线程的替代方法有哪些?

转载 作者:IT王子 更新时间:2023-10-29 04:21:36 27 4
gpt4 key购买 nike

自 .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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com