I have a windows service that has tasks and those tasks run a parallel foreach to process some images.
What I need to do now is have the service onstop method allow the tasks to complete their processing for items which are already under way but no allow any new items to begin.
Below are some fragments of my code to show what I have:
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();
}
As you can see I am stopping adding new items to process but I am still that the service is stopping before everything is finished up.
Any ideas??
Cheers
You would need to call ParallelLoopState.Stop to prevent processing of any new records. For details, see How to: Stop or Break from a Parallel.For Loop.