为什么我的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
发布于 2009-09-23 19:14:14
嗯..。它看起来确实应该可以工作,但我建议你一开始就不要使用Interrupt。使用事件和/或Monitor.Wait/Pulse来告诉线程您想要停止。这通常是一种更简单的方法,并且可以让工作线程更好地控制有序的停止。
https://stackoverflow.com/questions/1468014
复制相似问题