How can I convert a foreach to Parallel.ForEach?

2019-02-15 08:31发布

问题:

how to convert:

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

To somthing like This

 Parallel.ForEach(    NotifyCollectionChangedEventHandler handler in delegates) {
  ... 
 }

回答1:

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



回答2:

Here, quite easily:

Parallel.ForEach(delegates, handler => 
                            {
                                 //Do your thing with the handler and may the thread-safety be with you.
                            });

Although it should be quite obvious after reading the docs.



回答3:

Simple example from MSDN.

  // A simple source for demonstration purposes. Modify this path as necessary. 
string[] files = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");
string newDir = @"C:\Users\Public\Pictures\Sample Pictures\Modified";
System.IO.Directory.CreateDirectory(newDir);

//  Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
Parallel.ForEach(files, currentFile =>
{
    // The more computational work you do here, the greater  
    // the speedup compared to a sequential foreach loop. 
    string filename = System.IO.Path.GetFileName(currentFile);
    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(currentFile);

    bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
    bitmap.Save(System.IO.Path.Combine(newDir, filename));

    // Peek behind the scenes to see how work is parallelized. 
    // But be aware: Thread contention for the Console slows down parallel loops!!!
    Console.WriteLine("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId);

    } //close lambda expression
); //close method invocation 


回答4:

With some additions to the Action<TSource> parameter argument for your purpose:

Parallel.ForEach(delegates, d => { ... });