2012-07-19 96 views
2

我有一個Windows服務有任務和這些任務運行並行foreach來處理一些圖像。任務.net4和窗口服務停止

我現在需要做的是讓服務onstop方法允許任務完成對已經在進行的項目的處理,但不允許任何新項目開始。

下面是我的一些代碼片段,顯示我有什麼:

if (recordsToProcess != null && recordsToProcess.Any()) 
     { 
      if (!_cancellationTokenSource.Token.IsCancellationRequested) 
      { 
       Parallel.ForEach(recordsToProcess, new ParallelOptions { MaxDegreeOfParallelism = MaxParallelThreadSetting }, currentRecord => _Processor.Process(currentRecord, _supportedFileTypes)); 
      } 

      Task.WaitAll(); //Recently added not sure if needed 
     } 

protected override void OnStop() 
    { 
     //Sets the cancel flag to stop the processing 
     _cancellationTokenSource.Cancel(); 
     //Allows existing threads to complete 
     _logHandler.LogInfoMessage("Waiting On Cancel"); 
     Task.WaitAll(); 

     //Stop service and tidy up resources 
     _logHandler.LogInfoMessage("Stopping service"); 
     base.OnStop(); 
} 

正如你可以看到我停止添加新項目的過程,但我仍然認爲一切都結束了之前的服務正在停止。

任何想法??

乾杯

回答

0

您需要調用ParallelLoopState.Stop,以防止任何新記錄處理。有關詳細信息,請參見How to: Stop or Break from a Parallel.For Loop

+0

確定已經添加了,但這仍然使我停止服務的問題?? – Morn 2012-07-19 16:06:45

+0

@Morn你可能想要在循環停止時使用'ManualResetEvent'或類似的信號發送服務。 – 2012-07-19 16:07:34