Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Successive .NET Parallel For's - Blocking after each

I have several Parallel.For operations in succession.

I am currently examining each Parallel.For's return value ParallelLoopResult and sleeping for 20 milliseconds until the IsCompleted member is set to true.


Dim plr as ParallelLoopResult 

plr = Parallel.For(...)

while not plr.IsCompleted
  Thread.Sleep(20)
end while

plr = Parallel.For(...)

while not plr.IsCompleted
  Thread.Sleep(20)
end while

.
.
.

How can I add a kernel level block (i.e. WaitHandle) in place of the loop and Thread.Sleep? Is there a completion event that Parallel.For triggers? Does Parallel.For provide for such a mechanism?

like image 844
ColorEyes Avatar asked Nov 01 '10 14:11

ColorEyes


2 Answers

The Parallel.For will complete all code that it was called for. The IsCompleted only returns false then the loop was interrupted.

From http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopresult.aspx:

If IsCompleted returns true, then the loop ran to completion, such that all iterations of the loop were executed. If IsCompleted returns false and LowestBreakIteration returns null, a call to Stop was used to end the loop prematurely. If IsCompleted returns false and LowestBreakIteration returns a non-null integral value, Break was used to end the loop prematurely.

like image 52
Pieter van Ginkel Avatar answered Oct 11 '22 17:10

Pieter van Ginkel


You cant get WaitHandle for Parallel.For() and you dont need to - call is synchronous (all iterations will be completed after call is finished). If you need to execute loop itself on other thread, not only iterations, you must wrap it in Task or Thread, and that objects will provide you wait handles. But if you are goint to wait for results on the same thread as you call Parallel.For() (as in your sample code), it doesn't make any sense.

like image 45
max Avatar answered Oct 11 '22 15:10

max