【问题标题】:How can I convert a foreach to Parallel.ForEach?如何将 foreach 转换为 Parallel.ForEach?
【发布时间】:2013-02-11 10:32:25
【问题描述】:

如何转换:

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

像这样的东西

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

【问题讨论】:

    标签: c# task-parallel-library


    【解决方案1】:

    你可以这样做:

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

    考虑以下示例

    List<string> list = new List<string>()
    {
        "ABC",
        "DEF", 
        "EFG"
    };
    
    Parallel.ForEach(list, str =>
    {
        Console.WriteLine(str);
    });
    

    您可能还会看到:How to: Write a Simple Parallel.ForEach Loop

    【讨论】:

      【解决方案2】:

      在这里,很容易:

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

      虽然阅读文档后应该很明显。

      【讨论】:

        【解决方案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 
        

        【讨论】:

        • Bitmap 对象不会在每次迭代时泄漏内存吗?
        【解决方案4】:

        为您的目的添加了一些 Action&lt;TSource&gt; 参数参数:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-03-10
          • 2012-08-28
          • 1970-01-01
          • 1970-01-01
          • 2014-03-16
          • 2018-01-19
          • 1970-01-01
          • 2015-12-12
          相关资源
          最近更新 更多