Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a foreach to Parallel.ForEach?

how to convert:

  foreach (  NotifyCollectionChangedEventHandler handler in delegates) {
            ...
  }

To somthing like This

 Parallel.ForEach(    NotifyCollectionChangedEventHandler handler in delegates) {
  ... 
 }
like image 589
persianLife Avatar asked Feb 11 '13 10:02

persianLife


People also ask

Does ForEach work in parallel?

ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.

Is parallel ForEach faster than ForEach?

The execution of Parallel. Foreach is faster than normal ForEach.

Can you change a ForEach loop?

Why C#'s foreach loop cannot change what it loops over. With a foreach loop we easily iterate over all elements in a collection. During each pass through the loop, the loop variable is set to an element from a collection.

How do you write parallel ForEach in C#?

To use Parallel. ForEach loop we need to import System. Threading. Tasks namespace in using directive.


1 Answers

You can do:

Parallel.ForEach(delegates, handler => 
{ 
//your stuff 
});

Consider the following example

List<string> list = new List<string>()
{
    "ABC",
    "DEF", 
    "EFG"
};

Parallel.ForEach(list, str =>
{
    Console.WriteLine(str);
});

You may also see: How to: Write a Simple Parallel.ForEach Loop

like image 82
Habib Avatar answered Sep 21 '22 22:09

Habib