You are previewing Mastering C# Concurrency.
O'Reilly logo
Mastering C# Concurrency

Book Description

Create robust and scalable applications along with responsive UI using concurrency and the multi-threading infrastructure in .NET and C#

About This Book

  • Learn to combine your asynchronous operations with Task Parallel Library

  • Master C#’s asynchronous infrastructure and use asynchronous APIs effectively to achieve optimal responsiveness of the application

  • An easy-to-follow, example-based guide that helps you to build scalable applications using concurrency in C#

  • Who This Book Is For

    If you are a C# developer who wants to develop modern applications in C# and wants to overcome problems by using asynchronous APIs and standard patterns, then this book is ideal for you. Reasonable development knowledge, an understanding of core elements and applications related to the .Net platform, and also the fundamentals of concurrency is assumed.

    What You Will Learn

  • Apply general multithreading concepts to your application’s design

  • Leverage lock-free concurrency and learn about its pros and cons to achieve efficient synchronization between user threads

  • Combine your asynchronous operations with Task Parallel Library

  • Make your code easier with C#’s asynchrony support

  • Use common concurrent collections and programming patterns

  • Write scalable and robust server-side asynchronous code

  • Create fast and responsible client applications

  • Avoid common problems and troubleshoot your multi-threaded and asynchronous applications

  • In Detail

    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.

    Style and approach

    An easy-to-follow, example-based guide that will walk you through the core principles of concurrency and multithreading using C#.

    Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the code file.

    Table of Contents

    1. Mastering C# Concurrency
      1. Table of Contents
      2. Mastering C# Concurrency
      3. Credits
      4. About the Authors
      5. About the Reviewers
        1. Support files, eBooks, discount offers, and more
          1. Why subscribe?
          2. Free access for Packt account holders
          3. Instant updates on new Packt books
      7. Preface
        1. What this book covers
        2. What you need for this book
        3. Who this book is for
        4. Conventions
        5. Reader feedback
        6. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      8. 1. Traditional Concurrency
        1. What's the problem?
        2. Using locks
          1. Lock statement
          2. Monitor class
        3. Reader-writer lock
        4. Spin lock
          1. Thread.SpinWait
          2. System.Threading.SpinWait
          3. System.Threading.SpinLock
        5. Optimization strategy
          1. Lock localization
          2. Shared data minimization
        6. Summary
      9. 2. Lock-Free Concurrency
        1. Memory model and compiler optimizations
        2. The System.Threading.Interlocked class
        3. Interlocked internals
        4. Writing lock-free code
          1. The ABA problem
          2. The lock-free stack
          3. The lock-free queue
        5. Summary
      10. 3. Understanding Parallelism Granularity
        1. The number of threads
        2. Using the thread pool
        3. Understanding granularity
        4. Choosing the coarse-grained or fine-grained approach
        5. Summary
      11. 4. Task Parallel Library in Depth
        1. Task composition
        2. Tasks hierarchy
        3. Awaiting task completion
        4. Task cancellation
          1. Checking a flag
          2. Throwing an exception
          3. Using OS wait objects with WaitHandle
          4. Cancellation using callbacks
        5. Latency and the coarse-grained approach with TPL
        6. Exception handling
        7. Using the Parallel class
          1. Parallel.Invoke
          2. Parallel.For and Parallel.Foreach
          3. Understanding the task scheduler
        8. Summary
      12. 5. C# Language Support for Asynchrony
        1. Implementing the downloading of images from Bing
          1. Creating a simple synchronous solution
          2. Creating a parallel solution with Task Parallel Library
          3. Enhancing the code with C# 5.0 built-in support for asynchrony
          4. Simulating C# asynchronous infrastructure with iterators
        2. Is the async keyword really needed?
        3. Fire-and-forget tasks
        4. Other useful TPL features
          1. Task.Delay
          2. Task.Yield
        5. Implementing a custom awaitable type
        6. Summary
      13. 6. Using Concurrent Data Structures
        1. Standard collections and synchronization primitives
        2. Implementing a cache with ReaderWriterLockSlim
        3. Concurrent collections in .NET
        4. ConcurrentDictionary
          1. Using Lazy<T>
          2. Implementation details
            1. Lock-free operations
            2. Fine-grained lock operations
            3. Exclusive lock operations
          3. Using the implementation details in practice
        5. ConcurrentBag<T>
          1. ConcurrentBag in practice
        6. ConcurrentQueue<T>
        7. ConcurrentStack<T>
        8. The Producer/Consumer pattern
          1. Custom Producer/Consumer pattern implementation
        9. The Producer/Consumer pattern in .NET 4.0+
        10. Summary
      14. 7. Leveraging Parallel Patterns
        1. Concurrent idioms
          1. Process Tasks in Completion Order
          2. Limiting the parallelism degree
          3. Setting a task timeout
        2. Asynchronous patterns
          1. Asynchronous Programming Model
          2. Event-based Asynchronous Pattern
          3. Task-based Asynchronous Pattern
        3. Concurrent patterns
          1. Parallel pipelines
        4. Summary
      15. 8. Server-side Asynchrony
        1. Server applications
        2. The OWIN Web API framework
        3. Load testing and scalability
        4. I/O and CPU-bound tasks
        5. Deep dive into asynchronous I/O
        6. Real and fake asynchronous I/O operations
        7. Synchronization context
        8. CPU-bound tasks and queues
        9. Summary
      16. 9. Concurrency in the User Interface
        1. The importance of asynchrony for UI
        2. UI threads and message loops
        3. Common problems and solutions
        4. How the await keyword works
          1. Execution and synchronization contexts
        5. Performance issues
        6. Summary
      17. 10. Troubleshooting Parallel Programs
        1. How troubleshooting parallel programs is different
          1. Heisenbugs
        2. Writing tests
          1. Load tests
          2. Unit tests
        3. Integration tests
        4. Debugging
          1. Just my code setting
          2. Call stack window
          3. Threads window
          4. Tasks window
          5. Parallel stacks window
        5. Performance measurement and profiling
          1. The Concurrency Visualizer
        6. Summary
      18. Index