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!
Yes this possible. Look at this article that goes into detail about Parallel programming question. Here is an excerpt for you out of it:
using the traditional
StoporBreakdoes not cause the task to be canceled immediately, as you are experiencing. According to this article on MSDN,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!