Common pitfalls with parallelism
When working with the TPL, there are some practices to avoid in order to ensure the best outcomes in your applications. In some cases, parallelism used incorrectly can result in performance degradation. In other cases, it can cause errors or data corruption.
Parallelism is not guaranteed
When using one of the parallel loops or
Parallel.Invoke, the iterations can run in parallel, but they are not guaranteed to do so. The code in these parallel delegates should be able to run successfully in either scenario.
Parallel loops are not always faster
We discussed this earlier in this chapter, but it is important to remember that parallel versions of
foreach loops are not always faster. If each loop iteration runs quickly, the overhead of adding parallelism can slow down your application.
This is important to remember when introducing any threading to applications. Always test your code before and after introducing concurrency or parallelism...