April 2018
Intermediate to advanced
300 pages
7h 41m
English
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, ...
Read now
Unlock full access