- Introduction
- To Multithread or Not to Multithread?
- Multithreading with PLINQ
- Handling Concurrent Exceptions
- Processing Items with Parallel.ForEach
- Summary
To Multithread or Not to Multithread?
Some things, like file I/O, are inherently sequential. Other kinds of things can benefit from multithreading. Candidates for multithreading and parallel LINQ are algorithms that are computationally complex; for example, collections with very large data sets. Parallel LINQ (available by searching online for "parallel LINQ" or "PLINQ") is a download extension from Microsoft, in beta, that ultimately will let you write your LINQ queries and use multithreading too. The beauty, as you will see, is that most of the multithreading plumbing is handled for you by this extension to LINQ.
When you use PLINQ, keep a few things in mind:
Avoid adding ordering clauses.
Parallelize outer loops but not inner loops, unless the outer loop's range is very small (I equals 0 to 3) and the inner loop is very large (j equals 0 to 1000000).
Have reasonable expectations. Amdahl's Law suggests that the maximum achievable parallel speedup is limited by the amount of sequential code remaining. Everyone wants order-of-magnitude performance increases, but parallelism alone is unlikely to yield these sorts of returns. (Check out Amdahl's Law on Wikipedia.org for details and mathematics.)