Saturday, May 30, 2009

Breaking and Stopping Parallel Loop in Task Parallel Library

What if you want to exit from a Parallel.For method, like you could with for loop? You can not write code like this:

The problem here is that, For is a method of class Parallel. It is not a loop. And you can not exit from a method except with return statement.
The Solution:
TPL Team came with a great idea. You can pass in a delegate, which takes two parameters. On is the loop counter, and the other is of type class ParallelLoopState. ParallelLoopState has two methods to deal with exiting from loop:
Parallel.Break()
is shared with all other concurrent threads in the system which are participating in the loop's execution. After calling Break(), no additional iterations past the iteration of the caller will be executed on the current thread, and other parallel workers will be stopped at their earliest convenience.


Parallel.Stop()
is shared with all other concurrent threads in the system which are participating in the loop's execution. After calling Stop(), no additional iterations will be executed on the current thread, and other parallel workers will be stopped at their earliest convenience.

So, to stop the loop you should write the code as follows:


For a comprehensive overview of Parallel visit This Blog Post

No comments:

Post a Comment