I have something similar to this in my code:
Parallel.ForEach(myList, new ParallelOptions { MaxDegreeOfParallelism = 4 }, item =>
{
Process(item);
});
I ended up combining both options. It works but I don't know if this is the proper way to do this.
Solution:
Parallel.ForEach(myList, new ParallelOptions { MaxDegreeOfParallelism = 4 }, item =>
{
var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var token = tokenSource.Token;
Task task = Task.Factory.StartNew(() => Process(item, token), token);
task.Wait();
});
and in Process()
I check for cancellation multiple times:
private void Process(MyItem item, CancellationToken token)
{
try
{
if (token.IsCancellationRequested)
token.ThrowIfCancellationRequested();
...sentences
if (token.IsCancellationRequested)
token.ThrowIfCancellationRequested();
...more sentences
if (token.IsCancellationRequested)
token.ThrowIfCancellationRequested();
...etc
}
catch(Exception ex)
Console.WriteLine("Operation cancelled");