Book Image

Mastering C# Concurrency

Book Image

Mastering C# Concurrency

Overview of this book

Starting with the traditional approach to concurrency, you will learn how to write multithreaded concurrent programs and compose ways that won't require locking. You will explore the concepts of parallelism granularity, and fine-grained and coarse-grained parallel tasks by choosing a concurrent program structure and parallelizing the workload optimally. You will also learn how to use task parallel library, cancellations, timeouts, and how to handle errors. You will know how to choose the appropriate data structure for a specific parallel algorithm to achieve scalability and performance. Further, you'll learn about server scalability, asynchronous I/O, and thread pools, and write responsive traditional Windows and Windows Store applications. By the end of the book, you will be able to diagnose and resolve typical problems that could happen in multithreaded applications.
Table of Contents (17 chapters)
Mastering C# Concurrency
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Using the Parallel class


TPL provides a reach API to compose a parallel program. However, it is quite verbose, and if we write a simple code, there are easier way to parallelize it. For common tasks such as running some code in parallel and parallelizing the for and foreach loops, there is a Parallel class that provides a simple and easy to use API.

Parallel.Invoke

This method executes actions in parallel if the CPU has multiple cores and supports multiple threads. If the CPU has only one core, actions will be executed synchronously. This method blocks the calling thread until all the actions are completed:

Parallel.Invoke(
  () => Console.WriteLine("Action 1"),
  () =>
  {
    Thread.SpinWait(10000);
    Console.WriteLine("Action 2");
  },
  () => Console.WriteLine("Action 3"));
Console.WriteLine("End");

After running the preceding lines of code, we get the following output:

Action 1
Action 3
Action 2
End

We can provide the ParallelOptions class instance to this method to configure...