Comment convertir un foreach en Parallel.ForEach?

comment convertir:

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

Pour quelque chose comme ça

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

Tu peux faire:

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

Considérez l’exemple suivant

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

Vous pouvez aussi voir: Comment: écrire une boucle simple Parallel.ForEach

Ici, assez facilement:

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

Bien que cela devrait être assez évident après avoir lu la documentation.

Exemple simple de MSDN .

  // A simple source for demonstration purposes. Modify this path as necessary. ssortingng[] files = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg"); ssortingng newDir = @"C:\Users\Public\Pictures\Sample Pictures\Modified"; System.IO.Directory.CreateDirectory(newDir); // Method signature: Parallel.ForEach(IEnumerable source, Action body) Parallel.ForEach(files, currentFile => { // The more computational work you do here, the greater // the speedup compared to a sequential foreach loop. ssortingng 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 

Avec quelques ajouts à l’argument de paramètre Action pour votre objective:

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