我怎么能转换一个foreach来Parallel.ForEach?(How can I conver

2019-07-19 17:29发布

如何转换:

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

为了财产以后像这样的

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

Answer 1:

你可以做:

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

请看下面的例子

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

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

您还可以看到: 如何:编写一个简单的Parallel.ForEach循环



Answer 2:

在这里,很容易:

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

虽然它应该是阅读文档后相当明显。



Answer 3:

从简单的例子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 


Answer 4:

添加了一些新的Action<TSource>你的目的参数变量:

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


文章来源: How can I convert a foreach to Parallel.ForEach?