Improving your C# Skills
上QQ阅读APP看书,第一时间看更新

Parallel.ForEach

The Parallel.ForEach is a multithreaded version of the classic foreach loop. The foreach loop runs on a single thread, whereas the Parallel.ForEach runs on multiple threads and utilizes multiple cores of the CPU, if available.

Here is a basic example using Parallel.ForEach on a list of documents that needs to be processed, and which contains an I/O-bound operation:

static void Main(string[] args) 
{ 
  List<Document> docs = GetUserDocuments(); 
  Parallel.ForEach(docs, (doc) => 
  { 
    ManageDocument(doc); 
  }); 
} 
private static void ManageDocument(Document doc) => Thread.Sleep(1000); 

To replicate the I/O-bound operation, we just added a delay of 1 second to the ManageDocument method. If you execute the same method using the foreach loop, the difference will be obvious.