Reputation: 75
I'm using Parallel.ForEach
for achieving parallelism, I was wondering is there any way that I can stop the execution of Parallel.ForEach
once any one the requests complete. For example consider the following code:
IEnumerable<string> myList = new List<string>() { "admin", "admin2", "admin3" };
CancellationTokenSource _tokenSource = new CancellationTokenSource();
Parallel.ForEach(myList,
admin_name =>
{
Console.WriteLine(admin_name);
});
The above code prints admin
,admin2
and admin3
. I want to stop further execution if any of the admin names is printed.
Is this achievable? Or is there any work around available?
I am open to suggestions and improvement.
Upvotes: 0
Views: 299
Reputation: 19416
There is an overload of Parallel.ForEach
which passes a ParallelLoopState
to your delegate, this can be use to break out of the Parallel.ForEach
, i.e:
Parallel.ForEach(myList, (admin_name, state) =>
{
Console.WriteLine(admin_name);
// Stop other iterations
state.Stop();
});
What you will need to bear in mind is that this will not be atomic, other delegates which have already started will continue to execute, unless they explicitly check state.IsStopped
.
Instead of ParallelLoopState.Stop()
you may desire ParallelLoopState.Break()
.
Some further information about Stop()
and Break()
can be found at How to: Stop or Break from a Parallel.For Loop.
Upvotes: 1