views:

35

answers:

1

I have the following code inside a bigger loop, after profiling my code I discovered that all the Parallel.For gain in execution speed is lost in the long time the Stop() method takes to complete. Is there any way to improve this? Maybe calling Thread.Sleep()?

Thanks.

Parallel.For(0, 1000, (i, loopState) => 
{ 
   if (a == b)
       loopState.Stop(); 
}); 
+2  A: 

I think you should use loopState.Break() method, since it is paralel for break keyword. The Stop method sets IsStopped flag, so that other iterations may check this flag and stop at their convenience. It does not stop the loop.

See Stop and Break on msdn

Alex Reitbort
this is correct answer! Stop is cooperative, means that threads should stop manually if IsStopped returns true. Break is imperative for all and doesn't require cooperation.
Andrey
Stop() should be faster as you can check here: msdn.microsoft.com/en-us/library/dd782827.aspx
devdept
@devdept: May be, but you must write code to pool IsStopped flag for it to work. Break just works. Do no take sentences out of context.
Alex Reitbort
@Andrey: Break will allow scheduled iterations to complete after it is called. Stop will allow running iterations to complete, but it will not schedule additional iterations after it is called.
Brian Rasmussen
@Brian Rasmussen i am not sure that i understood the difference. could you explain?
Andrey
@Andrey. Say you have a parallel loop that runs from 0 to 1000. If you break at index 100, Break will ensure that all iterations < 100 are completed before breaking. Stop on the other hand just stops the loop as early as possible.
Brian Rasmussen
@Brian Rasmussen The only possible way to break "as early as possible" is to call Thread.Abort, i know no other ways to break executing code.
Andrey
@Andrey. By "as early as possible" I meant "at the system's earliest convenience" as is the wording used by the documentation (http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate.break.aspx). The point being, that Break and Stop have very different semantics and that Break will actually allow further iterations to be scheduled.
Brian Rasmussen