Mastering C# Concurrency
eBook - ePub

Mastering C# Concurrency

  1. 284 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Mastering C# Concurrency

Book details
Book preview
Table of contents
Citations

About This Book

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#.

Frequently asked questions

Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes, you can access Mastering C# Concurrency by Eugene Agafonov, Andrew Koryavchenko in PDF and/or ePUB format, as well as other popular books in Informatique & Développement d'applications. We have over one million books available in our catalogue for you to explore.

Information

Year
2015
ISBN
9781785286650

Mastering C# Concurrency


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

Mastering C# Concurrency

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

Credits

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

About the Authors

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.

About the Reviewers

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...

Table of contents

  1. Mastering C# Concurrency