C# Threading Handbook
C# Threading Handbook 英文版C# Thre ading handbook @team ddu10. 4 The datainExample23610.5 Summary….24611. Chapter 7: Networking and Threading24611. 1 Networking in. NET........................................,.......24711.2 Creating the Sample application24911.3 Summary::.:::..·:.:.:::.::::·:.·:.::::.::::::·.::·:27512. Appendix A: Customer Support and Feedback27512.1 Errata.27612.2 forums.apress. com...::...:::..:::::.::aa.::.:.:27613. Index.27713. 1 Index a27713.2| ndex B,.27913.3 Index c27913. 4 Index D28013.5 Index E13.6 Index F.::::::::::28213.7 Index G28313.8 Index H28313. 9 Index I28413.10 Index j:...::.::.:::.:::::::.::..:.::.:..::.:::::::::.:.:28413. 11 Index L28513.12 Index m..28513 13 Index N28713 14 Index o∴28813.15 Index p28813 16 Index Q,28913.17 Index r28913.18|ndeⅹS,,29013.19 Index t29513.20 Index u30013.21 Index v30013.22 Index W..30114. List of Figures.,,,…,…:.::::....:.:.:::::::::::::a:.::::.::::::::::::302C# Threading handbook @team ddu1. Table of contentsC# Threading handbookby Tobin Titus et alsBN:1861008295APress, LLC o 2004 (288 pages)This book addresses the fundamental units of windowsand. NET programming-threads. Coverage includeshow. NET applications are executed, the life cycle of a threadin. NEt how the. Net Framework uses threads and more.Table of contentsC# Threading handbook_(?[????)Introduction(? [????D)Chapter 1(?[????]) -Defining ThreadsChapter 2(?[????] )- Threading in.NETChapter 3(? [????))-Working with ThreadsChapter 4(?[????.)- Threading Design PrinciplesChapter 5(?[????])-Scaling Threaded ApplicationsChapter 6(?[????])-Debugging and Tracing ThreadsChapter 7(? [???? 1 )-Networking and ThreadingAppendix A(?[????. ))-Customer Support and FeedbackIndex(?[???])List of Figures(?[????.)2. Back CoverThis book addresses the fundamental units of Windows and. Net programming- threads. a strongunderstanding of the role threads play in program execution how multiple threads can interact inorder to make efficient programs, and the pitfalls to beware of when developing multithreadedapplications, are all core to a developer's ability to develop effective C# programs. This book willcover how. NET applica tions are executed, the life cycle of a thread in. nET, how the. NET Frameworkuses threads how threads work in an event -driven environment how we can avoid race conditionsand deadlocks, how the activity of multiple threads can be synchronized and how to debugC# Thre a ng handbook @team ddUmultithreaded applications. We finish it off by describing the creation of a multithreaded networkapplicationWhat is great about this book?Threads are fundamental to the way GUI and server applications operate if your code is running ina GUI, then you're already writing code in a threaded environment. An asP. net page also runs in athreaded environment this book aims to cover the tricky issues of threading in. net, andparticularly to do so from the perspective of C# developers. threading is by nature not easy to grasp,but a necessary step towards mastery of programming for the. NET platform3. C# Threading handbookApressTobin TitusFabio claudio FerracchiatiTejaswi Re dkarSrinivasa sivakumarCopyright c 2004 by Apress(This book was originally published by Wrox Press in 2003.All rights reserved. No part of this work may be reproduced or transmitted in any form or by anymeans, electronic or mechanical, including photocopying, recording or by any informationstorage or retrieval system, without the prior written permission of the copyright owner and thepublisheISBN(pbk):1-86100-829-5Printed and bound in the united states of america 10987654321Trademarked names may appear in this book. Rather than use a trademark symbol with everyoccurrence of a trademarked name, we use the names only in an editorial fashion and to thebenefit of the trademark owner, with no intention of infringement of the trademarkDistributed to the book trade in the United States by Springer-Verlag New York, Inc, 175 FifthAvenue, New York, NY, 10010 and outside the United States by Springer-Verlag GmbH & CoKG, Tiergartenstr. 17, 69112 Heidelberg, GermanyIn the United States: phone 1-800-SPRINGER, email , or vsithttp://www.springer-ny.com.OutsidetheUnitedstAtes:fax+496221345229,emailinger.de>,orvsithttp:/www.springer.deC# Thre ading handbook @team dduFor information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219Berkeley,CA94710Phone510-549-5930,fax510-549-5939,email,orvisithttttp:/www.apress.comThe information in this book is distributed on an"as is" basis, without warranty. Although everyprecaution has been taken in the preparation of this work, neither the author(s) nor Apress shhave any liability to any person or entity with respect to any loss or damage caused or alleged tobe caused directly or indirectly by the information contained in this workThesourcecodeforthisbookisavailabletoreadersathttp://www.apress.cominthedownloadssectionCreditsAuthorsTobin titusFabio claudio ferracchiatiTeiaswi RedkarSrinivasa sivakumarAdditional materialKouros h ardestaniSandra GopikrishnaAndrew polshawCommissioning EditorsNick ManningAndrew polshawTechnical EditorsJames hartNick ManningDouglas pattersonProject ManagerBeckie stonesManaging EditorEmma batch technical reviewersKouros h ardestaniRichard bonneauMark HomerCraig McQueenSaurabh nanduErick GarbDavid WhitneyC# Thre ading handbook @team dduPublisherJan kolasinskiIndexMichael brinkmanProduction coordinatorNeil loteProof readerChris SmithCoverNatalie O'DonnellAbout the authorsTobin titusTobin has several years of experience in software development and in the consulting industHe started working with BASIC in the 5th grade on an Atari 800XL computer. With the release ofVisual Basic, Tobin moved to Windows programming and has been developing Windows andweb-based solutions ever since. Tobin specializes in internet applications solutions with visualBasic, Java, and now microsoft. net tools-VB. net, Ct, and asP. net. he is also authoringtheBrainbenchcertificationexamonVisualBasic.Net(www.brainbench.com).CurrentlyTobindoes work for some of the best companies in the world including his own -Dax Software andConsultingLlc(www.daxsoftware.comThank s go to everyone who has supported me in my career. To the staff at Bethel Christian HighSchool in Penns ylvania and Bob ones University in South Carolina, thank you for your unfailingfaith and uncompromising positions. Thanks go to Carol, for putting up with my never-endingwork schedule. Special thanks to my parents who sacrificed so much for our family. Andspecial loving memory to my Grandmother Helm who was always able to encourage me to dobetter with just a simple hug-and maybe a little taste of fudgeC# Thre ading handbook @team dduFabio claudio ferracchiatiFabio Claudio Ferracchiati is a software developer and technical writer. In the early years of histen-year career he worked with classical languages and old Microsoft tools like visual Basicand visual C++. After fi ve years he decided to dedicate his attention to the Internet and all therelated technologies. In 1998 he started a parallel career writing technical articles for ltalian andinternationalmagazinesHeworksinRomeforCpiProgettiSpa(http://www.cpiprogetti.it),wherehe develops Internet/Intranet solutions using Microsoft technologies. Fabio would like to thankWrox for the chance to write this bookDedication to Danila: As in every book/ write and will wite, a special thank you goes to myunique love. You cant imagine how is important to have a woman like her near me in the happyand sad moments that life gives to us. love you so muchTejaswi RedkarC# Thre ading handbook @team dduTejaswi Redkar is a software evangelist. He holds a master's degree in Engineering from SanJose State University, California. His areas of interest include designing scalable multi-tiereddistributed applications and new generation embedded devices. Recently he filed a patent forhis innovations in managing telemetry gateways. When he is not working he can be found eatingexotic foodI would like to thank Wrox press for giving me the opportunity to express my ideas througharticles. I would also like to thank my dear wife Arohi for continuing to motivate meSrinivasa sivakumarSrinivasa Sivakumar is a software consultant, developer, and writer. He specializes in web andmobile technologies using Microsoft solutions. He currently works at Chicago for Trans TechLLC. He has co-authored various books, including Professional ASP. NET Web ServicesASP NE T Mobile Controls -Tutorial Guide,. NET Compact Framework, Beginning ASP NET1.0with VB. NET, Professional ASP NE T Security, The Complete Visual C#f Programmer'sReference Guide, and. NET Compact Frame work. He has also written technical articles for ASPToday, C# Today, NE T Developer, and more. In his free time he likes to watch Tamil movesand listen to Tamil sound tracks(Especially ones sung by Mr. S P Balasubramaniyam)The book takes a top-down look at how exactly. NET executes C# code. We begin by describingwhat a Windows thread is, and how they relate to. NET processes, application domains, andthreads. We examine thread scheduling(how the operating system decides which thread toprocess next), then look at how we write NET code to work with threads. Then we look at threadsynchronization, so that we can safely allow multiple threads to access the same resources. Welook at some ty pical architectures that multithreaded programs employ, in particular threadooling. We also examine how to debug multithreaded code. We finish with a fully workedexample showing how threading can help us build a scalable, high performance network serverC# Thre ading handbook @team ddu4. IntroductionMultithreading is what enables complex applications to appear to be performing numerous tasksat the same time. They may respond to user events, while at the same time accessing networkresources, or the file system. Such concurrent applications are written in different waysdepending on the platform and the operating system, giving varying control over this processVisual Basic 6, for instance, gave you little or no control, and it would implement threadingbehind the scenes, so that when an event occurred, it would execute the appropriate handlingcode within a particular threading model, but the application programmer never needed toconcern themself with it. Visual C++ developers had access to the full complexity of theWindows threading and process model, but with great power comes great responsibility: C++programmers could easily create multithreaded monsters, and had to learn and use a range ofcomplex tricks to ensure that the threads were kept under controlThe NET Framework's managed coding environment has made available a full and powerfulthreading model that allows you to control exactly what runs in a thread, when the thread exitsand how much data it should have access to. However, just as the Common Language Runtimehas taken responsibility for memory management out of the hands of programmers it has alsotaken much of the responsibility for managing and cleaning up threads. So, in. NET we have ahappy medium between the power of C++ and the simplicity of visual Basic. That said,multithreaded applications introduce a whole range of programming problems thatsingle-threaded programs never encounterThis book will teach you how to take advantage of the threading capabilities provided bythe. NET Framework, guiding you through the various features made available to you, whilepointing out pitfalls for you to avoidWhen is threading used? Well, in fact, all programs execute in threads, so understandinghow. NET and Windows execute threads will help you understand just what's going on insideyour program at run time. Windows Forms applications use event-loop threads to handle userinterface events. Separate forms execute on separate threads, so if you need to communicatebetween Windows Forms, you need to communicate between threads. ASP. NET pages executeinside the multi-threaded environment of lis-separat e requests for the same page may executeon different threads, and the same page may be executing on more than one threadsimultaneously. When accessing shared resources from an aSP. NET page, you'll encounterthreading issuesAs well as writing code that is executed in a multithreaded envronment such as this, we oftenneed to take control and actively create and control our own threads. Perhaps you need tocreate an application that never or rarely waits while processing some data, and is permanentlyavailable to respond to users and events. This can only happen if you build a multithreadedapplication. You can find many articles on the Web, and chapters in other books that tell youhow to create a thread with the. NET Framework and how to perform some rudimentaryoperations; however, implementing the code is only half of the story. When you are using a
用户评论