为什么我的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);
}
}
我已经完成了代码。我可以看到中断被调用(睡眠或等待当时不是活动命令),我可以看到睡眠被调用,但是没有抛出中断错误(无论是在睡眠上,还是在WaitOne上,即使是线程也是如此)在WaitOne上阻止。
我做错了什么?
注意:.Net 2.0
答案 0 :(得分:3)
嗯......看起来确实应该有效,但我建议你不要先使用Interrupt
。使用事件和/或Monitor.Wait
/ Pulse
告诉线程您要停止。这是一种通常更简单的方法,可以让工作者线程更有条理地控制停止。