ebook img

Multithreading with C# Cookbook PDF

264 Pages·2016·2.05 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Multithreading with C# Cookbook

Multithreading with C# Cookbook Second Edition Over 70 recipes to get you writing powerful and efficient multithreaded, asynchronous, and parallel programs in C# 6.0 Eugene Agafonov BIRMINGHAM - MUMBAI Multithreading with C# Cookbook Second Edition Copyright © 2016 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 author, 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: November 2013 Second Edition: April 2016 Production reference: 1150416 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78588-125-1 www.packtpub.com Credits Author Copy Editor Eugene Agafonov Neha Vyas Reviewers Project Coordinator Chad McCallum Francina Pinto Philip Pierce Proofreader Commissioning Editor Safis Editing Edward Gordon Indexer Acquisition Editor Rekha Nair Kirk D'Costa Production Coordinator Content Development Editor Manu Joseph Nikhil Borkar Cover Work Technical Editor Manu Joseph Vivek Pala About the Author Eugene Agafonov leads the development department at ABBYY and lives in Moscow. He has over 15 years of professional experience in software development, and he started working with C# when it was in beta version. He is 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, eugeneagafonov.com, or find him on Twitter at @eugene_agafonov. ABBYY is a global leader in the development of document recognition, content capture, and language-based technologies and solutions that are integrated across the entire information life cycle. He is the author of Multhreading in C# 5.0 Cookbook and Mastering C# Concurrency by Packt Publishing. I'd like to dedicate this book to my dearly beloved wife, Helen, and son, Nikita. About the Reviewers Chad McCallum is a Saskatchewan computer geek with a passion for software development. He has over 10 years of .NET experience (and 2 years of PHP, but we won't talk about that). After graduating from SIAST Kelsey Campus, he picked up freelance PHP contracting work until he could pester iQmetrix to give him a job, which he's hung onto for the last 10 years. He's come back to his roots in Regina and started HackREGINA, a local hackathon organization aimed at strengthening the developer community while coding and drinking beer. His current focus is mastering the art of multitenant e-commerce with .NET. Between his obsession with board gaming and random app ideas, he tries to learn a new technology every week. You can see the results at www.rtigger.com. Philip Pierce is a software developer with 20 years of experience in mobile, web, desktop, and server development, database design and management, and game development. His background includes creating A.I. for games and business software, converting AAA games between various platforms, developing multithreaded applications, and creating patented client/server communication technologies. Philip has won several hackathons, including Best Mobile App at the AT&T Developer Summit 2013, and a runner up for Best Windows 8 App at PayPal's Battlethon Miami. His most recent project was converting Rail Rush and Temple Run 2 from the Android platform to Arcade platforms. Philip's portfolios can be found at the following websites: f http://www.rocketgamesmobile.com f http://www.philippiercedeveloper.com www.PacktPub.com eBooks, discount offers, and more Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why Subscribe? f Fully searchable across every book published by Packt f Copy and paste, print, and bookmark content f On demand and accessible via a web browser Table of Contents Preface v Chapter 1: Threading Basics 1 Introduction 2 Creating a thread in C# 2 Pausing a thread 6 Making a thread wait 7 Aborting a thread 8 Determining a thread state 10 Thread priority 12 Foreground and background threads 14 Passing parameters to a thread 16 Locking with a C# lock keyword 19 Locking with a Monitor construct 22 Handling exceptions 24 Chapter 2: Thread Synchronization 27 Introduction 27 Performing basic atomic operations 28 Using the Mutex construct 31 Using the SemaphoreSlim construct 32 Using the AutoResetEvent construct 34 Using the ManualResetEventSlim construct 36 Using the CountDownEvent construct 38 Using the Barrier construct 39 Using the ReaderWriterLockSlim construct 41 Using the SpinWait construct 44 i Table of Contents Chapter 3: Using a Thread Pool 47 Introduction 47 Invoking a delegate on a thread pool 49 Posting an asynchronous operation on a thread pool 52 A thread pool and the degree of parallelism 54 Implementing a cancellation option 56 Using a wait handle and timeout with a thread pool 59 Using a timer 61 Using the BackgroundWorker component 63 Chapter 4: Using the Task Parallel Library 67 Introduction 67 Creating a task 69 Performing basic operations with a task 70 Combining tasks 72 Converting the APM pattern to tasks 75 Converting the EAP pattern to tasks 79 Implementing a cancelation option 81 Handling exceptions in tasks 83 Running tasks in parallel 85 Tweaking the execution of tasks with TaskScheduler 87 Chapter 5: Using C# 6.0 93 Introduction 93 Using the await operator to get asynchronous task results 96 Using the await operator in a lambda expression 98 Using the await operator with consequent asynchronous tasks 100 Using the await operator for the execution of parallel asynchronous tasks 102 Handling exceptions in asynchronous operations 104 Avoiding the use of the captured synchronization context 107 Working around the async void method 111 Designing a custom awaitable type 114 Using the dynamic type with await 118 Chapter 6: Using Concurrent Collections 123 Introduction 123 Using ConcurrentDictionary 125 Implementing asynchronous processing using ConcurrentQueue 127 Changing asynchronous processing order with ConcurrentStack 130 Creating a scalable crawler with ConcurrentBag 132 Generalizing asynchronous processing with BlockingCollection 136 ii Table of Contents Chapter 7: Using PLINQ 141 Introduction 141 Using the Parallel class 143 Parallelizing a LINQ query 145 Tweaking the parameters of a PLINQ query 148 Handling exceptions in a PLINQ query 151 Managing data partitioning in a PLINQ query 153 Creating a custom aggregator for a PLINQ query 157 Chapter 8: Reactive Extensions 161 Introduction 161 Converting a collection to an asynchronous Observable 162 Writing custom Observable 165 Using the Subjects type 168 Creating an Observable object 172 Using LINQ queries against an observable collection 174 Creating asynchronous operations with Rx 177 Chapter 9: Using Asynchronous I/O 181 Introduction 181 Working with files asynchronously 183 Writing an asynchronous HTTP server and client 187 Working with a database asynchronously 190 Calling a WCF service asynchronously 194 Chapter 10: Parallel Programming Patterns 199 Introduction 199 Implementing Lazy-evaluated shared states 200 Implementing Parallel Pipeline with BlockingCollection 205 Implementing Parallel Pipeline with TPL DataFlow 210 Implementing Map/Reduce with PLINQ 215 Chapter 11: There's More 221 Introduction 221 Using a timer in a Universal Windows Platform application 223 Using WinRT from usual applications 227 Using BackgroundTask in Universal Windows Platform applications 230 Running a .NET Core application on OS X 237 Running a .NET Core application on Ubuntu Linux 240 Index 243 iii

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.