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?
You don't need that with Parallel. Foreach: it only executes the foreach in as many thread as there are processors available, but it returns synchronously. Show activity on this post. As everyone here said - you dont need to wait for it.
The execution of Parallel. Foreach is faster than normal ForEach.
Since the work in your parallel function is very small, the overhead of the management the parallelism has to do becomes significant, thus slowing down the overall work.
ForEach loop runs on multiple threads and the processing takes place in a parallel manner.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With