5

如何转换:

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

像这样的东西

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

4 回答 4

18

你可以做:

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

考虑以下示例

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

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

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

于 2013-02-11T10:37:51.957 回答
0

在这里,很容易:

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

尽管阅读文档后应该很明显。

于 2013-02-11T10:35:45.787 回答
0

来自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 
于 2013-02-11T10:36:18.810 回答
0

Action<TSource>为了您的目的,对参数参数进行了一些补充:

Parallel.ForEach(delegates, d => { ... });
于 2013-02-11T10:36:39.023 回答