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

Preface

Recent C# and .NET developments involve implicitly using asynchrony and concurrency, even when you are not aware of them. This can lead to further problems since many details are usually hidden inside the C# language infrastructure and the .NET base class library APIs. To avoid problems and to be able to create robust applications, a developer has to know exactly what is going on under the hood of asynchrony in .NET.

Besides this, it is important to understand your goals when writing a concurrent application. If it is running on the client, it is usually a good thing to use all the computational resources available so that the application becomes as fast as possible. This involves effective multiple CPU cores usage, and thus requires parallel programming skills. However, if the application is running on the server, it is more important that the server supports as many clients as possible, than the performance of a concrete client request processing. This requires a programmer to distinguish asynchrony from multithreading and have an understanding of scalability.

All these topics will be covered in this book, providing you with enough information to achieve a solid understanding of asynchronous and parallel programming in C#. We will start with basic multithreading concepts, review common concurrent programming problems and solutions, and then we will go through C# and .NET support for writing concurrent applications. Further in the book, we will cover concurrent data structures and patterns, and we will review client-side and server-side concurrency issues. At the end of the book, we will outline the basic principles for creating robust concurrent programs.

What this book covers

Chapter 1, Traditional Concurrency, covers common problems with multithreading and solutions to these problems. You will refresh your knowledge about basic locking techniques and how to make locking more efficient.

Chapter 2, Lock-Free Concurrency, goes further into performance optimization. It covers various ways to write concurrent programs without locking, making the code fast and reliable.

Chapter 3, Understanding Parallelism Granularity, explains another important aspect of organizing your parallel code—splitting a computational workload between threads. It introduces coarse-grained and fine-grained approaches, showing their pros and cons.

Chapter 4, Task Parallel Library in Depth, goes into the details of Task Parallel Library—a framework to organize your concurrent program as a set of related tasks. You will find the internals of TPL reviewed and explained.

Chapter 5, C# Language Support for Asynchrony, is a deep dive into the C# language infrastructure. The chapter shows exactly how the async and await keywords work and how you can write your own await-compatible code.

Chapter 6, Using Concurrent Data Structures, covers the use of data structures in a concurrent program in detail, including standard .NET concurrent collections and custom thread safe collections implementations.

Chapter 7, Leveraging Parallel Patterns, reviews programming patterns related to parallel applications. The chapter describes different kinds of patterns—historical .NET idioms, useful code snippets, and a high-level parallel pipeline pattern.

Chapter 8, Server-Side Asynchrony, is a solution description to the problem of using asynchrony on the server. It explains why it is very important to distinguish asynchrony from parallelism, and how it can affect the scalability and reliability of your server.

Chapter 9, Concurrency in the User Interface, describes the details of how the user interface is implemented, what a message loop is, and why it is very important to keep the UI thread nonblocked.

Chapter 10, Troubleshooting Parallel Programs, explains how to find out what is wrong with your parallel program. You will learn how to write unit tests for an asynchronous code, how to debug it, and find performance bottlenecks.

What you need for this book

You will need Visual Studio 2013 or 2015 to run the code samples. For most of the chapters, it will be enough to use the free Visual Studio Community 2013/2015 editions, but the performance test samples will require the Test/Ultimate or Enterprise editions. However, if you cannot use this, it is possible to download the free Apache bench tool to run performance tests as described in the book.

Who this book is for

Mastering C# Concurrency is written for existing C# developers who have a knowledge of basic multithreading concepts and want to improve their asynchronous and parallel programming skills. The book covers different topics, from basic concepts to complicated programming patterns and algorithms using the C# and .NET ecosystems. This will be useful to server and client developers, because it covers all the important aspects of using concurrency and asynchrony on both sides.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "This happens because the Add method of the List<T> class is not thread safe, and the reason for this lies in the implementation details."

A block of code is set as follows:

public void Add(T item)
{
    if (_size == _items.Length) EnsureCapacity(_size + 1);
    _items[_size++] = item;
    _version++;
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

public void Add(T item)
{
    if (_size == _items.Length) EnsureCapacity(_size + 1);
    _items[_size++] = item;
    _version++;
}

Any command-line input or output is written as follows:

T2: Add - [T2]: Item 1
T1: Add - [T1]: Item 1
T2: Add - [T2]: Item 2
T2: Add - [T2]: Item 3

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Click on Finish and repeat all this for another controller."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.