2009-09-23 51 views
3

爲什麼我的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

+0

+1爲清楚和公開。 – 2009-09-23 19:12:05

回答

3

嗯......它看起來像它應該工作,但我勸你不要擺在首位使用Interrupt。使用事件和/或Monitor.Wait/Pulse來告訴線程你想停止。這是一種簡單的方法,可以讓工作線程更有序地停止。

+0

我喜歡中斷方法,因爲它會自動踢出我的_ProcessingWaitHandle.WaitOne(); – 2009-09-23 19:23:54

+2

Jon是對的。這是爲什麼:http://www.bluebytesoftware.com/blog/PermaLink,guid,c3e634ac-4aa1-44eb-a744-02d6ed4de514.aspx – 2009-09-23 19:27:06

+0

C.羅斯:等待句柄的一點是,你可以設置它沒有隻是中斷線程... – 2009-09-23 19:28:13