2013-02-11 64 views
2

如何轉換:轉換的foreach到Parallel.ForEach C#

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

爲了財產以後像這種

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

SO比文檔更快更可讀。恕我直言,這提出了具體的問題和@哈比卜提供了一個很好的答案,也在G搜索中排名第一。我upvote。 – 2014-04-10 08:01:22

回答

9

你可以這樣做:

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

0

在這裏,很容易:

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

雖然它應該是相當明顯閱讀文檔後。

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 
+0

每次迭代都不會有'Bitmap'對象泄漏內存嗎? – 2014-04-24 04:39:01

0

添加了一些新的Action<TSource>參數變量爲你的目的:

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