Timeout for Action in Parallel.ForEach iteration

Santiago Aceñolaza picture Santiago Aceñolaza · Mar 25, 2014 · Viewed 11.7k times · Source

I have something similar to this in my code:

Parallel.ForEach(myList, new ParallelOptions { MaxDegreeOfParallelism = 4 }, item =>
{
    Process(item);
});

The thing is that I do a bunch of things inside Process() method (connect to a file share, parse a file, save to db, etc) and I worry that something might go wrong during this process making the iteration never finish...could this ever happen?

Is there a way to set a timeout for the Process() method to avoid ending up having zombie threads?

UPDATE:

The easiest way I've found for setting a timeout is by adding milliseconds to a CancellationTokenSource or calling the Wait() method on a task.

Option #1

Parallel.ForEach(myList, new ParallelOptions { MaxDegreeOfParallelism = 4 }, item =>
{
    var cts = new CancellationTokenSource(2000);
    Task task = Task.Factory.StartNew(() => Process(item), cts.Token);
});

Option #2

Parallel.ForEach(myList, new ParallelOptions { MaxDegreeOfParallelism = 4 }, item =>
{
    Task task = Task.Factory.StartNew(() => Process(item));
    task.Wait(2000);
});

The problem is that none of those options are able to cancel the Process() method. Do I need to check for something in the Process() method?

Answer

poy picture poy · Mar 25, 2014

Consider adding CancellationToken to your code. This way, at any point you can properly cancel all the operations.

Then, you can use the CancelAfter() method.