Table of Contents
Mastering C# Concurrency
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Instant updates on new Packt books
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Traditional Concurrency
What's the problem?
Using locks
Lock statement
Monitor class
Reader-writer lock
Spin lock
Thread.SpinWait
System.Threading.SpinWait
System.Threading.SpinLock
Optimization strategy
Lock localization
Shared data minimization
Summary
2. Lock-Free Concurrency
Memory model and compiler optimizations
The System.Threading.Interlocked class
Interlocked internals
Writing lock-free code
The ABA problem
The lock-free stack
The lock-free queue
Summary
3. Understanding Parallelism Granularity
The number of threads
Using the thread pool
Understanding granularity
Choosing the coarse-grained or fine-grained approach
Summary
4. Task Parallel Library in Depth
Task composition
Tasks hierarchy
Awaiting task completion
Task cancellation
Checking a flag
Throwing an exception
Using OS wait objects with WaitHandle
Cancellation using callbacks
Latency and the coarse-grained approach with TPL
Exception handling
Using the Parallel class
Parallel.Invoke
Parallel.For and Parallel.Foreach
Understanding the task scheduler
Summary
5. C# Language Support for Asynchrony
Implementing the downloading of images from Bing
Creating a simple synchronous solution
Creating a parallel solution with Task Parallel Library
Enhancing the code with C# 5.0 built-in support for asynchrony
Simulating C# asynchronous infrastructure with iterators
Is the async keyword really needed?
Fire-and-forget tasks
Other useful TPL features
Task.Delay
Task.Yield
Implementing a custom awaitable type
Summary
6. Using Concurrent Data Structures
Standard collections and synchronization primitives
Implementing a cache with ReaderWriterLockSlim
Concurrent collections in .NET
ConcurrentDictionary
Using Lazy<T>
Implementation details
Lock-free operations
Fine-grained lock operations
Exclusive lock operations
Using the implementation details in practice
ConcurrentBag<T>
ConcurrentBag in practice
ConcurrentQueue<T>
ConcurrentStack<T>
The Producer/Consumer pattern
Custom Producer/Consumer pattern implementation
The Producer/Consumer pattern in .NET 4.0+
Summary
7. Leveraging Parallel Patterns
Concurrent idioms
Process Tasks in Completion Order
Limiting the parallelism degree
Setting a task timeout
Asynchronous patterns
Asynchronous Programming Model
Event-based Asynchronous Pattern
Task-based Asynchronous Pattern
Concurrent patterns
Parallel pipelines
Summary
8. Server-side Asynchrony
Server applications
The OWIN Web API framework
Load testing and scalability
I/O and CPU-bound tasks
Deep dive into asynchronous I/O
Real and fake asynchronous I/O operations
Synchronization context
CPU-bound tasks and queues
Summary
9. Concurrency in the User Interface
The importance of asynchrony for UI
UI threads and message loops
Common problems and solutions
How the await keyword works
Execution and synchronization contexts
Performance issues
Summary
10. Troubleshooting Parallel Programs
How troubleshooting parallel programs is different
Heisenbugs
Writing tests
Load tests
Unit tests
Integration tests
Debugging
Just my code setting
Call stack window
Threads window
Tasks window
Parallel stacks window
Performance measurement and profiling
The Concurrency Visualizer
Summary
Index
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: October 2015
Production reference: 1231015
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-665-0
www.packtpub.com
Authors
Eugene Agafonov
Andrew Koryavchenko
Reviewers
Tim Gabrhel
Michael Berantzino Hansen
Güray Özen
Simon Soanes
Acquisition Editor
Reshma Raman
Content Development Editor
Zeeyan Pinheiro
Technical Editor
Menza Mathew
Copy Editors
Kausambhi Majumdar
Alpha Singh
Project Coordinator
Suzanne Coutinho
Proofreader
Safis Editing
Indexer
Rekha Nair
Production Coordinator
Melwyn Dsa
Cover Work
Melwyn Dsa
Eugene Agafonov leads the Lingvo Live development department at ABBYY, and he lives and works in Moscow. He has over 15 years of professional experience in software development and has been working with C# ever since it was in beta version. He has been a Microsoft MVP in ASP.NET since 2006, and he often speaks at local software development conferences, such as DevCon Russia, about cutting-edge technologies in modern web and server-side application development. His main professional interests are cloud-based software architecture, scalability, and reliability. Eugene is a huge fan of football and plays the guitar with a local rock band. You can reach him at his personal blog at eugeneagafonov.com or his Twitter handle at @eugene_agafonov
.
He also wrote Multithreading in C# 5.0 Cookbook by Packt Publishing.
Andrew Koryavchenko is a software developer and an architect who lives in Moscow, Russia. He is one of the founders of rsdn.ru—the largest Russian software developers' community portal.
His specialty is ERP systems and developer tools. He participated in ReSharper Visual Studio extension development, which is a well-known productivity tool for .NET developers. Currently, he is working on parsing and compilation tools for .NET development and also supports and develops the rsdn.ru portal.
Andrew regularly speaks at online and offline events and conferences dedicated to Microsoft technologies, and he publishes articles on software development topics. He also used to teach Enterprise Software Development course in Kuban State University.
Andrew has been a Microsoft MVP in C# since 2005.
Tim Gabrhel is a senior application developer at Concurrency Inc., with a core focus on Microsoft Azure and modern .NET technologies. He is a creator and maker and loves being hands-on with new technologies and making them work in real life. Tim has been a consultant for Fortune 100 companies. He has contributed to the architecture and key components of enterprise solutions that have reached hundreds of thousands of users around the world. You can follow Tim and his technical journey at his blog, http://timgabrhel.com.
Michael Berantzino Hansen is a MCPD .NET Enterprise Application Developer specializing in high performance and efficient frameworks. He has been programming since the mid 80s from the age of 9. He started with Basic and then moved on to C++. In 1999, he earned a bachelors degree in computer science, economics, and organizational development, while working part time for ground-breaking startup...