为什么我的Thread.Interrupt不工作?
执行中断的代码:
public void Stop()
{
const string LOG_SOURCE = "ProcessingDriver";
if (_Enabled)
{
try
{
RequestProcessor.Disable();
if (ProcessingThread != null)
{
ProcessingThread.Interrupt();
ProcessingThread.Join();
}
}
catch (Exception ex)
{
WriteLog(LOG_SOURCE, ex);
}
}
}
我希望停止的代码:
private void ProcessRequests()
{
const string LOG_SOURCE = "ProcessRequests";
try
{
ProcessingThread = Thread.CurrentThread;
while (!_Disposed)
{
_ProcessingWaitHandle.WaitOne();
int count = GetRequestCount();
while (count > 0)
{
try
{
ExportRequest er = GetRequest();
ProcessRequest(er);
}
catch (ThreadInterruptedException)
{
throw;
}
catch (Exception ex)
{
WriteLog(LOG_SOURCE,
ex);
WriteLog(LOG_SOURCE,
"Request Failed.");
}
//Suspend to catch interupt
Thread.Sleep(1);
count = GetRequestCount();
}
}
}
catch (ThreadInterruptedException)
{
WriteLog(LOG_SOURCE,
"Interupted. Exiting.", LogType.Info);
}
catch (Exception critEx)
{
//Should never get here
WriteLog(LOG_SOURCE, critEx);
WriteLog(LOG_SOURCE,
"Serious unhandled error. Please restart.", LogType.Critical);
}
}
我已经逐步完成了代码。我可以看到中断被调用( sleep 或等待不是当时的事件命令),我可以看到 sleep 被调用,但没有抛出中断错误(无论是在 sleep 上,还是在 WaitOne 上,即使线程在 WaitOne 上阻塞)。
我做错了什么?
注意:.Net 2.0
最佳答案
嗯...它看起来确实应该工作,但我建议您首先不要使用 Interrupt
。使用事件和/或 Monitor.Wait
/Pulse
告诉线程您要停止。这是一种通常更简单的方法,并且可以让工作线程更好地控制有序停止。
关于c# - Thread.Interrupt 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1468014/