CHAPTER 19 MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING
private void btnGetStats_Click(object sender, EventArgs e)
{
// Get the words from the e-book.
string[] words = theEBook.Split(
new char[] { ' ', '\u000A', ',', '.', ';', ':', '-', '?', '/' },
StringSplitOptions.RemoveEmptyEntries);
string[] tenMostCommon = null;
string longestWord = string.Empty;
Parallel.Invoke(
() =>
{
// Now, find the ten most common words.
tenMostCommon = FindTenMostCommon(words);
},
() =>
{
// Get the longest word.
longestWord = FindLongestWord(words);
});
}
// Now that all tasks are complete, build a string to show all
// stats in a message box.
...
The Parallel.Invoke() method expects a parameter array of Action<> delegates, which you have
supplied indirectly using lambda expressions. Again, while the output is identical, the benefit is that the
TPL will now make use of all possible processors on the machine to invoke each method in parallel if
possible.
Source Code The MyEBookReader project is included under the Chapter 19 subdirectory.
Parallel LINQ Queries (PLINQ)
To wrap up your look at the TPL, be aware that there is another way you can incorporate parallel tasks
into your .NET applications. If you choose, you can make use of a set of extension methods, which allow
you to construct a LINQ query that will perform its workload in parallel (if possible). Fittingly, LINQ
queries that are designed to run in parallel are termed PLINQ queries.
Like parallel code authored using the Parallel class, PLINQ has the option of ignoring your request
to process the collection in parallel if need be. The PLINQ framework has been optimized in numerous
ways, which includes determining whether a query would, in fact, perform faster in a synchronous
manner.
At runtime, PLINQ analyzes the overall structure of the query, and if the query is likely to benefit
from parallelization, it will run concurrently. However, if parallelizing a query would hurt performance,
PLINQ just runs the query sequentially. If PLINQ has a choice between a potentially expensive parallel
algorithm or an inexpensive sequential algorithm, it chooses the sequential algorithm by default.
741