可能重复的问题:Is there a way to indefinitely pause a thread?
在我的代码中,我执行以下操作
Thread mainThread
//...
mainThread.Resume();
void StartThread()
{
while (!wantQuit)
{
db.runEmail();
mainThread.Suspend();
}
}
然后我得到下面的异常,因为我在它没有被挂起时调用了 resume。
System.Threading.ThreadStateException
我注意到这个警告
warning CS0618: 'System.Threading.Thread.Resume()' is obsolete: 'Thread.Resume has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. http://go.microsoft.com/fwlink/?linkid=14202'
所以我想知道有没有办法恢复并忽略未暂停的异常/情况?我讨厌写下面而不是一行
try
{
mainThread.Resume();
}
catch (System.Threading.ThreadStateException e)
{
}
最佳答案
简单的解决方案是修复您的逻辑,并且当您未处于 Suspended() 时不要调用 Resume()。
但 Resume/Suspend API 确实已被弃用,例如:
1) Monitor , 等待() 和脉冲()
2) AutoResetEvent或 ManualResetEvent、Set() 和 WaitOne()
静态类 Monitor 更易于使用并与 lock() {}
集成,但 ResetEvent 在这里可能更合适,因为您可以在 set 或 unset 模式下创建它,并且您是不太可能“错过”信号。相比之下,当 Wait() 稍后发生时,Monitor.Pulse() 将丢失。
将在您的问题中插入一个链接,虽然我不认为它是重复的,the accepted answer非常适合解决您使用挂起/恢复的问题。
关于c# - 恢复 C# 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1369212/