Reputation: 18513
In C#, is it possible to immediately exit a Parallel.For loop that is in progress. The following code can take up to a full second to exit the loop after loopState.Stop() has been called.
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
Parallel.For(0, 50, (i, loopState) =>
{
Console.WriteLine("Thread:" + Thread.CurrentThread.ManagedThreadId + "\tIteration:" + i);
Thread.Sleep(1000);
if (i == 0)
{
watch.Start();
loopState.Stop();
return;
}
});
Console.WriteLine("Time Elapsed since loopState.Stop(): {0}s", watch.Elapsed.TotalSeconds);
Console.ReadKey();
}
Output
Thread:10 Iteration:0
Thread:6 Iteration:12
Thread:11 Iteration:24
Thread:12 Iteration:36
Thread:13 Iteration:48
Thread:13 Iteration:49
Thread:12 Iteration:37
Time Elapsed since loopState.Stop(): 0.9999363s
Is there any way to do this faster? Thanks!
Upvotes: 1
Views: 2157
Reputation: 3258
Yes this possible. Look at this article that goes into detail about Parallel programming question. Here is an excerpt for you out of it:
What if I don’t want to waste resources and want to stop all computations immediately after I click Cancel? In this case, I have to periodically check for the status of the cancellation token somewhere within the method that performs the long-running operation. Since I declared the cancellation token as a field, I can simply use it within the method.
public double SumRootN(int root)
{
double result = 0;
for (int i = 1; i < 10000000; i++)
{
tokenSource.Token.ThrowIfCancellationRequested();
result += Math.Exp(Math.Log(i) / root);
}
return result;
}
using the traditional Stop
or Break
does not cause the task to be canceled immediately, as you are experiencing. According to this article on MSDN,
In this context, "break" means complete all iterations on all threads that are prior to the current iteration on the current thread, and then exit the loop. "Stop" means to stop all iterations as soon as convenient.
So you can't force it to stop immediately using the traditional method. You will need to use a method like I mentioned at the beginning.
Hope this helps you!
Upvotes: 3
Reputation: 32576
The problem is the running time of the loop body. loopState.Stop()
stops any new loop iterations from beginning, and waits for any that are currently running to complete.
Upvotes: 1