OReilly dot NET gotchas may 2005 ISBN 0596009097

658 72 0
OReilly dot NET gotchas may 2005 ISBN 0596009097

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

.NET Gotachas By Venkat Subramaniam Publisher: O'Reilly Pub Date: May 2005 ISBN: 0-596-00909-7 Pages: 400 Table of Contents | Index Like most complex tasks, NET programming is fraught with potential costly, and timeconsuming hazards The millions of Microsoft developers worldwide who create applications for the NET platform can attest to that Thankfully there's now a book that shows you how to avoid such costly and time-consuming mistakes It's called NET Gotchas The ultimate guide for efficient, pain-free coding, NET Gotchas from O'Reilly contains 75 common NET programming pitfalls and advice on how to work around them It will help you steer away from those mistakes that cause application performance problems, or so taint code that it just doesn't work right The book is organized into nine chapters, each focusing on those features and constructs of the NET platform that consistently baffle developers Within each chapter are several "gotchas," with detailed examples, discussions, and guidelines for avoiding them No doubt about it, when applied, these concise presentations of best practices will help you lead a more productive, stress-free existence What's more, because code examples are written in both VB.NET and C#, NET Gotchas is of interest to more than 75 percent of the growing numbers of NET programmers So if you're a NET developer who's mired in the trenches and yearning for a better way, this book is most definitely for you NET Gotachas By Venkat Subramaniam Publisher: O'Reilly Pub Date: May 2005 ISBN: 0-596-00909-7 Pages: 400 Table of Contents | Index Copyright Dedication Preface Who This Book Is For What You Need to Use This Book Measure of Performance Conventions Used in This Book Using Code Examples Comments and Questions Safari® Enabled Acknowledgments Chapter 1 CLR/Framework Gotchas GOTCHA #1 Type alias size doesn't match what you're familiar with GOTCHA #2 struct and class differ in behavior GOTCHA #3 Returning value types from a method/property is risky GOTCHA #4 You can't force calls to your value-type constructors GOTCHA #5 String concatenation is expensive GOTCHA #6 Exceptions may go unhandled GOTCHA #7 Uninitialized event handlers aren't treated gracefully GOTCHA #8 Division operation isn't consistent between types GOTCHA #9 Typeless ArrayList isn't type-safe GOTCHA #10 Type.GetType() may not locate all types GOTCHA #11 Public key reported by sn.exe is inconsistent Chapter 2 Visual Studio and Compiler Gotchas GOTCHA #12 Compiler warnings may not be benign GOTCHA #13 Ordering of catch processing isn't consist across languages GOTCHA #14 Type.GetType() might fail at run-time GOTCHA #15 rethrow isn't consistent GOTCHA #16 Default of Option Strict (off) isn't good GOTCHA #17 Versioning may lead to Serialization headaches GOTCHA #18 Creating Web apps can be painful GOTCHA #19 Naming XML documentation for IntelliSense support isn't intuitive Chapter 3 Language and API Gotchas GOTCHA #20 Singleton isn't guaranteed process-wide GOTCHA #21 Default performance of Data.ReadXMLData.ReadXML GOTCHA #22 enum lacks type-safety GOTCHA #23 Copy Constructor hampers exensibility GOTCHA #24 Clone() has limitations GOTCHA #25 Access to static/Shared members isn't enforced consistently GOTCHA #26 Details of exception may be hidden GOTCHA #27 Object initialization sequence isn't consistent GOTCHA #28 Polymorphism kicks in prematurely GOTCHA #29 Unit testing private methodstesting private methods Chapter 4 Language Interoperability Gotchas GOTCHA #30 Common Language Specification Compliance isn't the default GOTCHA #31 Optional parameters break interoperability GOTCHA #32 Mixing case between class members breaks interoperability GOTCHA #33 Name collision with keywords breaks interoperability GOTCHA #34 Defining an array isn't consistent Chapter 5 Garbage Collection Gotchas GOTCHA #35 Writing Finalize() is rarely a good idea GOTCHA #36 Releasing managed resources in Finalize( ) can wreak havoc GOTCHA #37 Rules to invoke base.Finalize() aren't consistent GOTCHA #38 Depending on Finalize() can tie up critical resources GOTCHA #39 Using Finalize() on disposed objects is costly GOTCHA #40 Implementing IDisposable isn't enough GOTCHA #41 Using the Dispose Design Pattern doesn't guarantee cleanup Chapter 6 Inheritance and Polymorphism Gotchas GOTCHA #42 Runtime Type Identification can hurt extensibility GOTCHA #43 Using new/shadows causes "hideous hiding" GOTCHA #44 Compilers are lenient toward forgotten override/overrides GOTCHA #45 Compilers lean toward hiding virtual methods GOTCHA #46 Exception handling can break polymorphism GOTCHA #47 Signature mismatches can lead to method hiding Chapter 7 Multithreading Gotchas GOTCHA #48 The Thread classThread class GOTCHA #49 Foreground threads may prevent a program from terminating GOTCHA #50 Background threads don't terminate gracefully GOTCHA #51 Interrupt () kicks in only when a thread is blocked GOTCHA #52 ThreadAbortExceptiona hot potato GOTCHA #53 Environment.Exit() brings down the CLR GOTCHA #54 ResetAbort() may lead to surprises GOTCHA #55 Abort() takes time to clean up GOTCHA #56 Calling Type.GetType() may not return what you expect GOTCHA #57 Locking on globally visible objects is too sweeping GOTCHA #58 Threads from the thread pool are scarce GOTCHA #59 Threads invoked using delegates behave like background threads GOTCHA #60 Passing parameters to threads is tricky GOTCHA #61 Exceptions thrown from threads in the pool are lost GOTCHA #62 Accessing WinForm controls from arbitrary threads is dangerous GOTCHA #63 Web-service proxy may fail when used for multiple asynchronous calls GOTCHA #64 Raising events lacks thread-safety Chapter 8 COM-Interop and Enterprise Services Gotchas GOTCHA #65 Release of COM object is confusing GOTCHA #66 Using interface pointers after calling ReleaseComObject() will fail GOTCHA #67 Cross-apartment calls are expensive GOTCHA #68 Default apartment of main thread is inconsistent across languages GOTCHA #69 STAThread attribute may have no effect on your methods GOTCHA #70 Spattering access to COM components makes code hard to maintain GOTCHA #71 Auto-generating GUID for your classes leads to versioning woes GOTCHA #72 All but one of the ClassInterface options are ineffective GOTCHA #73 Simply tur ning the switch for COM interop is dangerous GOTCHA #74 ServicedComponents implemented inconsistently on XP and 2003 GOTCHA #75 AutoComplete comes with undesirable side effects Appendix: Resources Bibliography On the Web Colophon About the Author Colophon Index .NET Gotchas by Venkat Subramaniam Copyright © 2005 O'Reilly Media, Inc All rights reserved Printed in the United States of America Published by O'Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O'Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (safari.oreilly.com) For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com Editor: John Osborn Development Editor: Ralph Davis Production Editor: Philip Dangler Cover Designer: Ellie Volckhausen Interior Designer: Marcia Friedman Printing History: May 2005: First Edition Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly Media, Inc .NET Gotchas, the image of a hammerhead shark, and related trade dress are trademarks of O'Reilly Media, Inc Microsoft, MSDN, the NET logo, Visual Basic, Visual C++, Visual Studio, and Windows are registered trademarks of Microsoft Corporation Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O'Reilly Media, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein ISBN: 0-596-00909-7 [M] Dedication To my teachers:Mr J Govindaswamy, Dr Dayalan, Mrs Kranti Ramakrishnan, and Professor N Venkateswaran, who spent countless hours to motivate, inspire, and turn me around I dedicate achievements in my professional life to you Venkat Subramaniam Preface If you've picked up this book, you're probably among the many programmers who have come to appreciate how powerful the Microsoft NET Framework can be as a platform for development But you've also learned that, as with any platform, NET has quirks that can trip up even the savviest programmer Have you been surprised by feature behavior in the NET language or the NET Frameworkincluding the CLR and Framework Class Libraryor in Visual Studio NET? If you've worked with NET for any length of time, I suspect you are nodding your head with a sigh of agreement Experience teaches us what to do and what to avoid, but in programming, we commonly acquire our knowledge the hard way: by making costly, hard-to-debug and time-consuming mistakes My goal in writing this book is to save my fellow developers from some of that pain, by sharing the experiences (and bad code) that brought the pitfalls of NET to light for me, and showing you how to avoid them (and write code that works) I started working with NET when it was in pre-release Beta 2 The following years have been a lot of fun However, there have been days (and nights) when things were not so obvious, when the code would behave, shall I say, strangely, given my expectations as an experienced developer The gotchas and guidelines presented in this book have come from three sources: First, the insights I have gained from developing NET applications Second, the questions raised by the hundreds of inquisitive software developers I've had the privilege of training Third, the thought-provoking articles and discussions I have come across at symposiums, user-group meetings, the Internet, as well as the MSDN documentation itself What's a GOTCHA? According to Merriam-Webster, gotcha is defined as follows: "Main Entry: got:cha Pronunciation: 'gä-ch& Function: noun Etymology: alteration of got you : an unexpected usually disconcerting challenge, revelation For me, NET gotchas are those things that pop up unexpectedly when you're programming in NET Things that are buried, just waiting for you! It is as if the environment is there, aware of its own idiosyncrasies, watching you as you work, but unable (or unwilling) to warn you as you fall into one of its traps I'm not talking about those little annoying quirks in Visual Studio that make it misbehave occasionally, nor the transient flaws you see while working with the debugger or editor In this book, I focus on the NET Framework and language features that have consistently exhibited behavior that was not obvious to me Why should you be interested in learning about these? Because knowing these little gotchas will help you avoid mistakes You'll develop applications more quickly Some solutions will improve the performance of your applications Others will help you stay clear of problems that will make your code incorrect Yet others will help you with hidden problems such as proper garbage collection Most books on NET start by assuming that the reader knows little about it Those books are intended to bring readers up to speed with NET or one of its associated languages As more and more people learn to use any technology, a need arises not just to learn how use it, but how to use it well, and do things right Because experience is our best teacher, it always takes a few years for books that address those needs to appear Consider my own case, some years ago I had taken the time to learn the C# language and was a serious developer (or so I thought), working hard to put the features and facilities of the language to prudent use One day in the early '90s, I walked into my colleague's office and found a book entitled C++ FAQs by Marshal Cline on her table Picking it up, I asked "Why would anyone who knows C++ read a book that lists questions and answers?" She smiled I flipped through a few pages, and before I knew it, I found I had been standing there for several minutes reading the book, page after page She finally interrupted and said, "Why would anyone who knows C++ be reading that book for so long?" I found it to be invaluable and bought a copy for myself (and I still have that book and its next edition in my library!) Other great books that I have enjoyed reading are Effective C++ and More Effective C++ by Scott Meyers, Essential COM by Don Box et al., and Effective Jav a by Joshua Bloch Programming in NET has entered a stage where a large number of developers have learnt how to program what was a brand new platform only a few years ago The time has arrived for books that teach good practices I hope this book will serve, like the classics on COM and C++ that have preceded it, to educate software developers on the dos and don'ts of programming the NET platform ResetAbort() resources accessing managed freeing unmanaged unmanaged resources from NET returning a value type Richter, Jeffrey 2nd RTTI example of use extensibility and OCP and using in Play( ) method Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [L] [M] [N] [O] [P] [R] [S] [T] [U] [V] [W] [X] scripting COM component serialization examples C# VB.NET of a derived class SerializationInfo class ServicedComponent ServicedComponents inconsistencies various Windows platforms sessions, multiple calls when session is maintained SetExecutingThreadLabel( ) method SetPassword( ) method Shadows keyword shallow copy Shared members access to invoking usingreference object references and Shared method signatures changing in derived class mismatches method hiding overriding and overloading to change Single Threaded Apartment (STA) singleton example not guaranteed process-wide within AppDomain Singleton Design Pattern Singleton thread-safety sn utility to create key and extract public key token solutions versus projects Start( ) method STAThread effect of not setting in C# effect of using usage static variables static/Shared fields uniquess of static/Shared methods 2nd static/shared methods polymorphism static/Shared methods synchronization Stop( ) method 2nd Strict option off StringBuilder versus +/& struct keyword in C# Structure in VB.NET synchronization ineffective problems with synchronizing locally and precisely on metadata SyncLock block System.Data.DataSet class System.Enum.IsDefined( ) System.ICloneable interface System.Runtime.InteropServices.Marshal class System.Runtime.InteropServices.Marshal.ReleaseComObject( ) static/Shared method System.Timers.Timer object System.Timers.Timer's event handler System.Web.Services.Protocols.SoapException System.Windows.Forms.Control.Invoke( ) method 2nd System.Xml.XmlDocument parser class Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [L] [M] [N] [O] [P] [R] [S] [T] [U] [V] [W] [X] termination of background thread Test class Test Driven Development web site testing private methods Thread class Abort( ) Abort( ) method calling Join( ) method after Abort() behavior dangerous methods and properties Exit( ) method Interrupt( ) method IsAlive property IsBackground property Join( ) Pulse( ) ResetAbort( ) method 2nd Resume( ) method Suspend( ) method ThreadState property Wait( ) method thread pool thread safety form controls parameters raising events in thread-safe environment testing thread-safe objects ThreadAbortException 2nd ResetAbort( ) method and ThreadInterruptedException ThreadRunner class 2nd using threads abrupt termination of background thread background terminating behavior executing thread for different Timers and Delegate C# VB.NET exiting immortal interrupting parameters using your own thread versus one from thread pool throw statement 2nd using to propagate an exception Townsend, Mark Trainer class relying on polymorphic behavior of MakeNoise( ) method TransactionOption.Required transactions in Enterprise Services C# VB.NET Treat Warnings As Errors C# VB.NET try/catch statements type aliases mismatch Type metadata locking type-safe usage of enum Type.GetType( ) not type safe Type.GetType() behavior of failure typeof/GetType operator Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [L] [M] [N] [O] [P] [R] [S] [T] [U] [V] [W] [X] Unexpected Errors in Managed Applications web site unit testing unmanaged resources from NET using AutoDual exposing NET component using keyword 2nd Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [L] [M] [N] [O] [P] [R] [S] [T] [U] [V] [W] [X] value type no-parameter constructor of returned from a property, modifying returning VB FAQs web site VB.NET Catch order class derived from another class code examples Abort Aliases 2nd Apartment 2nd Array 2nd 3rd ArrayList 2nd 3rd BackgroundAbort BeginInvoke CatchOrder 2nd ClassInterfaceType 2nd 3rd 4th COMInterfaces ControlThread 2nd CopyingObjects 2nd 3rd 4th 5th 6th 7th 8th 9th 10th DataSetXMLSpeed DefaultApartment Delegate DifferInCase DisposeFinalize DivByZero 2nd EnumSafety 2nd ES 2nd ESAutoComplete 2nd ExceptionInDeriving 2nd 3rd 4th ExceptionInThread, client-side code 2nd ExceptionInThread, server-side code Finalize GetType 2nd GUID HandleException HandleException, client code HandleException, library code HidingMess Initialization Interrupt IsBackground JoinAbort KnowTheExit MethodSignature 2nd MultipleWSCalls MultipleWSCalls, client side MultipleWSCalls, server side No Example in VB.NET NotToFinalize 2nd Optional 2nd 3rd OptionStrict 2nd ParamThreadSafety 2nd 3rd 4th 5th 6th PolymorphismTooSoon RaisingEventThreadSafety RefactoredWrapper ReflectionToSerialize 2nd 3rd 4th RememberMarkOverride ResetAbortMethod ResourceHold Rethrow ReturningValueType 2nd RTTI 2nd 3rd 4th SettingApartment 2nd SingletonAppDomain 2nd StringAppend SuppressingFinalize Synchronizing 2nd 3rd 4th SynchWithIntent 2nd TestPrivate 2nd ThouShaltReleaseObject Typeof 2nd ValueReferenceTypes ValueTypeConstructor VirtualInDerived Warnings WhatsInAName 2nd XMLSerializer 2nd communicating with root object creating arrays deriving a VB.NET class from a C# class Dispose design pattern executing thread for different Timers and Delegate Finalize( ), writing as Protected Overrides method lost exception in asynchronous call, Web service multiple calls on web service client side server side RaiseEvent reflection to serialize and deserialize serialization example templates Treat Warnings As Errors unboxing in MSIL translated from writing Finalize() VB6 setting reference to Nothing versioning violation of LSP virtual/overridable methods 2nd 3rd 4th calling inside constructors polymorphism and with same name and signature exists in base class Visual Source Safe (VSS) Visual Studio warnings reported by Visual Studio debugger Disassembly VS.NET tips and tricks web site Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [L] [M] [N] [O] [P] [R] [S] [T] [U] [V] [W] [X] WaitForPendingFinalizers( ) method (GC class) warnings reported by Visual Studio treating as errors web service asynchronous access multiple concurrent requests WinForm app, unhandled exceptions in Wrapper and the Runtime Callable Wrapper (RCW) Wrapper class refactored wrapper classes Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [L] [M] [N] [O] [P] [R] [S] [T] [U] [V] [W] [X] XML documentation example documents parsing schema files preloading XMLSerializer class failure ... .NET Gotachas By Venkat Subramaniam Publisher: O'Reilly Pub Date: May 2005 ISBN: 0-596-00909-7 Pages: 400 Table of Contents | Index... Have you been surprised by feature behavior in the NET language or the NET Frameworkincluding the CLR and Framework Class Libraryor in Visual Studio NET? If you've worked with NET for any length of time, I suspect you are... programming the NET platform Who This Book Is For This book is intended for the NET programmer in the trenches This includes both C# and VB .NET programmers I assume that you are fairly familiar with NET programming using either C#

Ngày đăng: 19/04/2019, 13:44

Mục lục

  • .NET Gotachas

  • Table of Contents

  • Copyright

  • Dedication

  • Preface

    • Who This Book Is For

    • What You Need to Use This Book

    • Measure of Performance

    • Conventions Used in This Book

    • Using Code Examples

    • Comments and Questions

    • Safari® Enabled

    • Acknowledgments

    • Chapter 1.  CLR/Framework Gotchas

      • GOTCHA #1 Type alias size doesn't match what you're familiar with

      • GOTCHA #2 struct and class differ in behavior

      • GOTCHA #3 Returning value types from a method/property is risky

      • GOTCHA #4 You can't force calls to your value-type constructors

      • GOTCHA #5 String concatenation is expensive

      • GOTCHA #6 Exceptions may go unhandled

      • GOTCHA #7 Uninitialized event handlers aren't treated gracefully

      • GOTCHA #8 Division operation isn't consistent between types

Tài liệu cùng người dùng

Tài liệu liên quan