Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel For loops. Are they wait for finish?

Tags:

I have two for loops. which the second loop must be started after finishing the first loop.

So, If I use two Parallel.For() loops, will the second loop runs after the finishing the first loop?

like image 490
Mahdi Ghiasi Avatar asked Jan 06 '12 10:01

Mahdi Ghiasi


People also ask

Does parallel foreach wait for completion?

You don't have to do anything special, Parallel. Foreach() will wait until all its branched tasks are complete. From the calling thread you can treat it as a single synchronous statement and for instance wrap it inside a try/catch.

How do you wait for parallel to complete?

For already blocks your current thread till all tasks are done. Parallel. For doesn't return until its done. If you wrap it in a Task , then that task will complete at "exactly" the same point in time at which the Parallel.

How does a parallel loop work?

In a parallel loop, the restrictions on the ordering of the loop iterations are relaxed, which allows the iterations to execute – at least partially – in parallel. In the example, all iterations can execute in parallel, since they are completely independent of each other.

Is async await parallel C#?

With TPL we can implement Parallel Programming in C# . NET very easy. Async and Await keywords were introduced in C# 5.0 by Microsoft. When you use the “Async” keyword, you can write code the same way you wrote synchronous code.


1 Answers

Yes. Parallel.For will not return until all operations have completed.

If you run

Parallel.For(0, 5, i => Console.WriteLine("First {0}", i)); Console.WriteLine("First Finished"); Parallel.For(0, 5, i => Console.WriteLine("Second {0}", i)); Console.WriteLine("Second Finished"); 

The output is

First 0 First 2 First 1 First 4 First 3 First Finished Second 0 Second 4 Second 3 Second 2 Second 1 Second Finished 

The order of the integers will vary, but second will always come after first.

like image 110
Ray Avatar answered Oct 26 '22 23:10

Ray