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

Standard collections and synchronization primitives


To highlight what problems can appear when we use nonthread safe collections in a concurrent program, let's write a simple program that will use the Parallel.Foreach class to copy a collection and double its elements:

var source = Enumerable.Range(1, 42000).ToList();
var destination = new List<int>();
            
Parallel.ForEach(source, n => destination.Add(n * 2));
 
Assert.AreEqual(source.Count, destination.Count);

If we run this code, we will almost certainly get the AggregateException exception with the ArgumentException instance wrapped inside it.

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:

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

In case the concurrent threads access this method when the _size == items.Length – 1 condition is true, the ArgumentException...