如何将foreach转换为Parallel.ForEach?

5

如何转换:

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

将其转化为类似于这样的内容
 Parallel.ForEach(    NotifyCollectionChangedEventHandler handler in delegates) {
  ... 
 }
4个回答

19

你可以做:

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

考虑以下示例

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

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

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


1

来自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 

在每次迭代中,Bitmap对象不会泄漏内存吗? - Chris Schiffhauer

0

在这里,非常容易:

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

尽管在阅读文档后应该相当明显。


0

通过对Action<TSource>参数进行一些添加,以满足您的需求:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接