When using Parallel.ForEach()
, is there a way to forcefully execute Thread.Abort
on a specific thread?
I know that Thread.Abort()
is not recommended.
I'm running a Parallel.ForEach()
on a collection of a hundreds of thousands of entities.
The loop processes data going back 30 years in some cases. We've had a few issues where a thread hangs. While we are trying to get a grasp on that, was hoping to call implement a fail safe. If the thread runs for more than x amount of time, forcefully kill the thread.
I do not want to use a cancellation token.
It would be ugly, but haven't come to another solution. Would it be possible to:
- Have each thread open a timer. Pass in reference of
Thread.CurrentThread
to timer - If the timer elapses, and processing hasn’t completed, call
Thread.Abort
on that timer - If needed, signal event wait handle to allow next patient to process
private void ProcessEntity(ProcessParams param,
ConcurrentDictionary<long, string> entities)
{
var options = new ParallelOptions
{
MaxDegreeOfParallelism = 2
};
Parallel.ForEach(person, options, p =>
{
ProcessPerson(param, p);
});
}
internal void ProcessPerson(ProcessParams param, KeyValuePair<long, string> p)
{
try
{
//...
}
catch (Exception ex)
{
}
param.eventWaitHandle?.WaitOne();
}