Thread.Interrupt无法正常工作
为什么我的Thread.Interrupt无法正常工作?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
嗯......它看起来像它应该工作,但我劝你不要摆在首位使用Interrupt
。使用事件和/或Monitor.Wait
/Pulse
来告诉线程你想停止。这是一种简单的方法,可以让工作线程更有序地停止。
我喜欢中断方法,因为它会自动踢出我的_ProcessingWaitHandle.WaitOne(); – 2009-09-23 19:23:54
Jon是对的。这是为什么:http://www.bluebytesoftware.com/blog/PermaLink,guid,c3e634ac-4aa1-44eb-a744-02d6ed4de514.aspx – 2009-09-23 19:27:06
C.罗斯:等待句柄的一点是,你可以设置它没有只是中断线程... – 2009-09-23 19:28:13
+1为清楚和公开。 – 2009-09-23 19:12:05