Full Coverage of Multicore Programming
CLR via C#
T H I R D E D I T I O N
The definitive guide to mastering CLR and .NET
development—from the bottom up
Dig deep and master the intricacies of the common language
runtime, C#, and .NET development. Led by programming expert
Jeffrey Richter, a longtime consultant to the Microsoft® .NET team,
you’ll gain the pragmatic insights you need to build robust, reliable,
and responsive applications and components. Fully updated for
.NET Framework 4.0 and multicore programming, this classic guide
is ideal for developers building any type of application—including
Microsoft Silverlight®, ASP.NET, Windows® Presentation Foundation,
Web services, and console apps.
About the Author
Jeffrey Richter is a cofounder of Wintellect
(www.wintellect.com), a training, consulting, and
debugging firm dedicated to helping companies
build better software faster. He began consulting
for the Microsoft .NET Framework Team in
October 1999, and has contributed to a number
of Microsoft products. In addition to this book’s
previous editions, he’s written several other
popular titles, including Windows via C/C++
and Advanced Windows.
shared assemblies
Discover how to:
• Build, deploy, and version applications, components, and
• Understand how primitive, value, and reference types
behave to define and use them more efficiently
• Use generics and interfaces to define reusable algorithms
• Work effectively with special CLR types—delegates,
enumerators, custom attributes, arrays, strings
• Understand how the garbage collector manages resources
• Design responsive, reliable, and scalable solutions using the
• Use exception handling to assist with state management
• Construct dynamically extensible apps using CLR hosting,
AppDomains, assembly loading, reflection, and C#’s
dynamic type
thread pool, tasks, cancellation, timers, and asynchronous
I/O operations
Get C# code samples on the Web
And download the author’s “Power Threading Library”
See the Introduction
ISBN: 978-0-7356-2704-8
9 0 0 0 0
U.S.A. $59.99
[Recommended]
9 7 8 0 7 3 5 6 2 7 0 4 8
Programming/Windows
6
9
9
1
6
-
6
1
X
.
o
N
t
r
a
P
RESOURCE ROADMAP
Developer Step by Step
• Hands-on tutorial covering
fundamental techniques and features
• Practice files on CD
• Prepares and informs new-to-topic
programmers
Developer Reference
• Expert coverage of core topics
• Extensive, pragmatic coding examples
• Builds professional-level proficiency
with a Microsoft technology
Focused Topics
• Deep coverage of advanced
techniques and capabilities
• Extensive, adaptable coding examples
• Promotes full mastery of a
Microsoft technology
See inside cover
Full Coverage of Multicore Programming
CLR via C#
F O U R T H E D I T I O N
spine = 1.43”
C
L
R
v
i
a
C
#
H
I
E
D
I
T
I
4T
R
D
O
N
Richter
Microsof
Jeffrey Richter
prePresst
PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399
With Microsoft prePress, you can access just-written content from upcoming
books. The chapters come straight from our respected authors, before they’re
fully polished and debugged—for critical insights now, when you need them.
This document contains one or more portions of a preliminary version of a Microsoft Press title and is provided
“as is.” The content may be changed substantially upon final publication. In addition, this document may make
reference to pre-released versions of software products that may be changed substantially prior to final
commercial release. Microsoft reserves the right to not publish this title or any versions thereof (including
future prePress ebooks). This document is provided for informational purposes only. MICROSOFT MAKES NO
WARRANTIES, EITHER EXPRESS OR IMPLIED, IN THIS DOCUMENT. Information and views expressed in this
document, including URL and other Internet website references may be subject to change without notice. You
bear the risk of using it.
Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under
copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or
for any purpose, without the express written permission of Microsoft Corporation.
Some examples are for illustration only and are fictitious. No real association is intended or inferred. This
document does not provide you with any legal rights to any intellectual property in any Microsoft product,
service, or other offering.
© 2012 Microsoft Corporation. All rights reserved.
Microsoft and the trademarks listed at
http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the
Microsoft group of companies. All other marks are property of their respective owners.
Contents at a Glance
Part I
Chapter 1
Chapter 2
Chapter 3
CLR Basics
The CLR's Execution Mode
Building, Packaging, Deploying, and Administering
Applications and Types
Shared Assemblies and Strongly Named Assemblies
Designing Types
Type Fundamentals
Primitive, Reference, and Value Types
Type and Member Basics
Constants and Fields
Part II
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8 Methods
Parameters
Chapter 9
Chapter 10 Properties
Chapter 11
Chapter 12 Generics
Interfaces
Chapter 13
Events
Essential Types
Enumerated Types and Bit Flags
Part III
Chapter 14 Chars, Strings, and Working with Text
Chapter 15
Chapter 16 Arrays
Chapter 17 Delegates
Chapter 18 Custom Attributes
Chapter 19 Nullable Value Types
Core Facilities
Exceptions and State Management
Part IV
Chapter 20
Chapter 21 The Managed Heap and Garbage Collection
Chapter 22 CLR Hosting and App Domains
Chapter 23 Assembly Loading and Reflection
Chapter 24 Runtime Serialization
Chapter 25
Interoperating with WinRT Components
Part V
Threading
Chapter 26 Thread Basics
Chapter 27 Compute-Bound Asynchronous Operations
Chapter 28
Chapter 29 Primitive Thread Synchronization Constructs
Chapter 30 Hybrid Thread Synchronization Constructs
I/O-Bound Asynchronous Operations
Chapter 1
The CLR’s Execution Model
In this chapter:
Compiling Source Code into Managed Modules
Combining Managed Modules into Assemblies
Loading the Common Language Runtime
Executing Your Assembly’s Code
1
5
6
9
The Native Code Generator Tool: NGen.exe
18
The Framework Class Library
20
The Common Type System
22
The Common Language Specification
25
Interoperability with Unmanaged Code
29
The Microsoft .NET Framework introduces many concepts, technologies, and terms. My goal in this
chapter is to give you an overview of how the .NET Framework is designed, introduce you to some of
the technologies the framework includes, and define many of the terms you’ll be seeing when you start
using it. I’ll also take you through the process of building your source code into an application or a set
of redistributable components (files) that contain types (classes, structures, etc.) and then explain how
your application will execute.
Compiling Source Code into Managed Modules
OK, so you’ve decided to use the .NET Framework as your development platform. Great! Your first step
is to determine what type of application or component you intend to build. Let’s just assume that
you’ve completed this minor detail; everything is designed, the specifications are written, and you’re
ready to start development.
Now you must decide which programming language to use. This task is usually difficult because
different languages offer different capabilities. For example, in unmanaged C/C++, you have pretty
low-level control of the system. You can manage memory exactly the way you want to, create threads
easily if you need to, and so on. Microsoft Visual Basic 6, on the other hand, allows you to build UI
applications very rapidly and makes it easy for you to control COM objects and databases.
The common language runtime (CLR) is just what its name says it is: a runtime that is usable by
different and varied programming languages. The core features of the CLR (such as memory
management, assembly loading, security, exception handling, and thread synchronization) are available
to any and all programming languages that target it—period. For example, the runtime uses
exceptions to report errors, so all languages that target the runtime also get errors reported via
exceptions. Another example is that the runtime also allows you to create a thread, so any language
that targets the runtime can create a thread.
In fact, at runtime, the CLR has no idea which programming language the developer used for the
source code. This means that you should choose whatever programming language allows you to
express your intentions most easily. You can develop your code in any programming language you
desire as long as the compiler you use to compile your code targets the CLR.
So, if what I say is true, what is the advantage of using one programming language over another?
Well, I think of compilers as syntax checkers and “correct code” analyzers. They examine your source
code, ensure that whatever you’ve written makes some sense, and then output code that describes
your intention. Different programming languages allow you to develop using different syntax. Don’t
underestimate the value of this choice. For mathematical or financial applications, expressing your
intentions by using APL syntax can save many days of development time when compared to expressing
the same intention by using Perl syntax, for example.
Microsoft has created several language compilers that target the runtime: C++/CLI, C# (pronounced
“C sharp”), Visual Basic, F# (pronounced “F sharp”), Iron Python, Iron Ruby, and an Intermediate
Language (IL) Assembler. In addition to Microsoft, several other companies, colleges, and universities
have created compilers that produce code to target the CLR. I’m aware of compilers for Ada, APL,
Caml, COBOL, Eiffel, Forth, Fortran, Haskell, Lexico, LISP, LOGO, Lua, Mercury, ML, Mondrian, Oberon,
Pascal, Perl, PHP, Prolog, RPG, Scheme, Smalltalk, and Tcl/Tk.
Figure 1-1 shows the process of compiling source code files. As the figure shows, you can create
source code files written in any programming language that supports the CLR. Then you use the
corresponding compiler to check the syntax and analyze the source code. Regardless of which compiler
you use, the result is a managed module. A managed module is a standard 32-bit Microsoft Windows
portable executable (PE32) file or a standard 64-bit Windows portable executable (PE32+) file that
requires the CLR to execute. By the way, managed assemblies always take advantage of Data Execution
Prevention (DEP) and Address Space Layout Randomization (ASLR) in Windows; these two features
improve the security of your whole system.
C#
source code
file(s)
source code
Basic
file(s)
IL
source code
file(s)
C#
compiler
Basic
compiler
IL
Assembler
Managed module
(IL and metadata)
Managed module
(IL and metadata)
Managed module
(IL and metadata)
FIGURE 1-1 Compiling source code into managed modules.
Table 1-1 describes the parts of a managed module.
TABLE 1-1 Parts of a Managed Module
Part
Description
PE32 or PE32+ header
The standard Windows PE file header, which is similar to the Common Object File
Format (COFF) header. If the header uses the PE32 format, the file can run on a 32-bit
or 64-bit version of Windows. If the header uses the PE32+ format, the file requires a
64-bit version of Windows to run. This header also indicates the type of file: GUI, CUI, or
DLL, and contains a timestamp indicating when the file was built. For modules that
contain only IL code, the bulk of the information in the PE32(+) header is ignored. For
modules that contain native CPU code, this header contains information about the
native CPU code.
CLR header
Metadata
Contains the information (interpreted by the CLR and utilities) that makes this a
managed module. The header includes the version of the CLR required, some flags, the
MethodDef metadata token of the managed module’s entry point method (Main
method), and the location/size of the module’s metadata, resources, strong name, some
flags, and other less interesting stuff.
Every managed module contains metadata tables. There are two main types of tables:
tables that describe the types and members defined in your source code and tables that
describe the types and members referenced by your source code.
IL code
Code the compiler produced as it compiled the source code. At runtime, the CLR
compiles the IL into native CPU instructions.
Native code compilers produce code targeted to a specific CPU architecture, such as x86, x64, or
ARM. All CLR-compliant compilers produce IL code instead. (I’ll go into more detail about IL code later
in this chapter.) IL code is sometimes referred to as managed code because the CLR manages its
execution.
In addition to emitting IL, every compiler targeting the CLR is required to emit full metadata into
every managed module. In brief, metadata is a set of data tables that describe what is defined in the
module, such as types and their members. In addition, metadata also has tables indicating what the
managed module references, such as imported types and their members. Metadata is a superset of
older technologies such as COM’s Type Libraries and Interface Definition Language (IDL) files. The
important thing to note is that CLR metadata is far more complete. And, unlike Type Libraries and IDL,
metadata is always associated with the file that contains the IL code. In fact, the metadata is always
embedded in the same EXE/DLL as the code, making it impossible to separate the two. Because the
compiler produces the metadata and the code at the same time and binds them into the resulting
managed module, the metadata and the IL code it describes are never out of sync with one another.
Metadata has many uses. Here are some of them:
• Metadata removes the need for native C/C++ header and library files when compiling because
all the information about the referenced types/members is contained in the file that has the IL
that implements the type/members. Compilers can read metadata directly from managed
modules.
• Microsoft Visual Studio uses metadata to help you write code. Its IntelliSense feature parses
metadata to tell you what methods, properties, events, and fields a type offers, and in the case
of a method, what parameters the method expects.
•
The CLR’s code verification process uses metadata to ensure that your code performs only
“type-safe” operations. (I’ll discuss verification shortly.)
• Metadata allows an object’s fields to be serialized into a memory block, sent to another
machine, and then deserialized, re-creating the object’s state on the remote machine.
• Metadata allows the garbage collector to track the lifetime of objects. For any object, the
garbage collector can determine the type of the object and, from the metadata, know which
fields within that object refer to other objects.
In Chapter 2, “Building, Packaging, Deploying, and Administering Applications and Types,” I’ll
describe metadata in much more detail.
Microsoft’s C#, Visual Basic, F#, and the IL Assembler always produce modules that contain
managed code (IL) and managed data (garbage-collected data types). End users must have the CLR
(presently shipping as part of the .NET Framework) installed on their machine in order to execute any