Using the Parallel Class in C# – Run Tasks in Parallel on Multiple Processors or Cores
The Parallel Class can be used to split up the tasks which work on the data. For example if you have iterative code that looks like the below code:
//6 parts of the book
string[] inputTextFiles =
{
“part1.txt”, “part2.txt”, “part3.txt”,
“part4.txt”, “part5.txt”, “part6.txt”
};
foreach (string file in inputTextFiles)
{
string contentStr = File.ReadAllText(file);
CountCharacters(contentStr);
CountWords(contentStr);
}
The Parallel class can be used with lambda expressions to parallelize the two calculation methods:
foreach(string file in inputFiles)
{
string contentStr = File.ReadAllText(file);
Parallel.Invoke(
() => CountCharacters(contentStr),
() => CountWords(contentStr)
);
}
The results from using the Parallel Class to split tasks are normally not as dramatic as using Parallel to split data across processors but they are still significant.












No comments yet... Be the first to leave a reply!