- •Table of Contents
- •C# and the .NET Platform, Second Edition
- •Introduction
- •Part One: Introducing C# and the .NET Platform
- •Part Two: The C# Programming Language
- •Part Three: Programming with .NET Assemblies
- •Part Four: Leveraging the .NET Libraries
- •Part Five: Web Applications and XML Web Services
- •Obtaining This Book's Source Code
- •The .NET Solution
- •What C# Brings to the Table
- •The Role of the Assembly Manifest
- •Summary
- •Chapter 2: Building C# Applications
- •Summary
- •Chapter 3: C# Language Fundamentals
- •Defining Program Constants
- •Defining Custom Class Methods
- •C# Enumerations
- •Summary
- •The Second Pillar: C#'s Inheritance Support
- •Summary
- •Catching Exceptions
- •Finalizing a Type
- •Garbage Collection Optimizations
- •Summary
- •Chapter 6: Interfaces and Collections
- •Building Comparable Objects (IComparable)
- •Summary
- •Summary
- •Internal Representation of Type Indexers
- •Summary
- •An Overview of .NET Assemblies
- •Understanding Delayed Signing
- •Using a Shared Assembly
- •GAC Internals
- •Summary
- •Spawning Secondary Threads
- •A More Elaborate Threading Example
- •Summary
- •Summary
- •Object Persistence in the .NET Framework
- •The .NET Remoting Namespaces
- •Understanding the .NET Remoting Framework
- •All Together Now!
- •Terms of the .NET Remoting Trade
- •Testing the Remoting Application
- •Revisiting the Activation Mode of WKO Types
- •Deploying the Server to a Remote Machine
- •Summary
- •Control Events
- •The Form Class
- •Summary
- •Regarding the Disposal of System.Drawing Types
- •Understanding the Graphics Class
- •Summary
- •The TextBox Control
- •Working with Panel Controls
- •Configuring a Control's Anchoring Behavior
- •Summary
- •Chapter 16: The System.IO Namespace
- •The Static Members of the Directory Class
- •The Abstract Stream Class
- •Summary
- •The Role of ADO.NET Data Providers
- •The Types of System.Data
- •Selecting a Data Provider
- •The Types of the System.Data.OleDb Namespace
- •Working with the OleDbDataReader
- •Summary
- •Submitting the Form Data (GET and POST)
- •Some Benefits of ASP.NET
- •Creating an ASP.NET Web Application by Hand
- •The Composition of an ASP.NET Page
- •The Derivation of an ASP.NET Page
Summary C# and the .NET Platform, Second Edition
by Andrew Troelsen ISBN:1590590554
This chapter drilled into the details behind the innocent-looking .NET DLLs and EXEs located on your
Apress © 2003 (1200 pages)
development machine. You began the journey by examining the core concepts of the assembly: CLR
This comprehensive text starts with a brief overview of the
headers, metadata,C# manifests,language andandthenCILquickly. As illustratedmoves toinkeythistechnicalchapter,and.NET supports the notion of crosslanguage inheritance,ar hitecturaland to thisissuend,s foryou.NETreceiveddevelopersa glimpse. into the syntax of the VB .NET and MC++ programming language.
TableAs youf Contentshave seen, assemblies may be private or shared. In stark contrast to classic COM, private C#assembliesand the .NETarePlatform,the defaultSecond. WhenEditionyou wish to configure a shared assembly, you are making an explicit
choice, and need to generate a corresponding strong name. Recall that both private and shared
Intr duction
assemblies can be configured declaratively using a client side *.config file, or alternatively, a publisher
Part One - Introducing C# and the .NET Platform
policy *.dll.
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
This chapter wrapped up by quickly examining a set of related assembly-centric details: the
Part Two - The C# Programming Language
machine.config file, the .NET configuration utility (to simplify the process of building XML configuration
Chapter 3 - C# Language Fundamentals
files), ngen.exe (to prejit CIL code at the time of installation); and you learned how to inform VS .NET to
Chapter 4 - Object-Oriented Programming with C#
display your custom .NET binaries within the Add References dialog.
Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
Chapter C#10:andProcesses,the .NET Platform, SecondAppDomains,Editi n Contexts, and
by Andrew Troelsen ISBN:1590590554
Threads Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
In the previous chapter, you examined the steps taken by the CLR to resolve the location of an externally
architectural issues for .NET developers.
referenced assembly. Here, you drill deeper into the constitution of a .NET executable host and come to understand the relationship between Win32 processes, application domains, contexts, and threads. In a nutshell,applicationdomains (or simply, AppDomains) are logical subdivisions within a given process, which host a set of related .NET assemblies. As you will see, an application domain is further subdivided
into contextual boundaries, which are used to group together like-minded .NET objects. Using the notion of
Introduction
context, the CLR is able to ensure that objects with special needs are handled appropriately.
Part One - Introducing C# and the .NET Platform
ChaptOnceryou1 -haveThecomePhilosophyto understandof .NET the relationship between processes, application domains, and
Chapcontexts,r 2 the- BuildingremainderC# Applicationsof this chapter examines how the .NET platform allows you to manually spawn
PartmultipleTwo -threadsThe C# ofProgrammiexecutiongforLanguageuse by your program within its application domain. Using the types within
Chapterthe System3 -.ThreadingC# L nguagenamespace,Fundamentalsthe task of creating additional threads of execution has become Chapterextremely4 -simpleObject(if-Orientednot downrightPro rammingtrivial).withOf course,C# the complexity of multithreaded development is not in
the creation of threads, but in ensuring that your code base is well equipped to handle concurrent access
Chapter 5 - Exceptions and Object Lifetime
to shared resources. Given this, the chapter closes by examining various synchronization primitives that
Chapter 6 - Interfaces and Collections
the .NET Framework provides (which you will see is somewhat richer than raw Win32 threading
Chapter 7 - Callback Interfaces, Delegates, and Events
primitives).
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
ChapterReviewing9 - UnderstandingProcesses.NET Assembliesand Threads Under Traditional Win32
Chapter 10 - Processes, AppDomains, Contexts, and Threads
The concept of processes and threads has existed within Windows-based operating systems well before
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
the release of the .NET platform. Simply put, process is the term used to describe the set of resources
Part Four - Leveraging the .NET Libraries
(such as external code libraries and the primary thread) as well as the necessary memory allocations used
Chapter 12 - Object Serialization and the .NET Remoting Layer
by a running application. For each *.exe loaded into memory, the operating system creates a separate and isolated memory partition (aka process) for use during its lifetime. Using this approach to application
isolation, the result is a much more robust and stable runtime environment, given that the failure of one
Chapter 15 - Programming with Windows Forms Controls process does not effect the functioning of another.
Chapter 16 - The System.IO Namespace
ChapterNow, every17 - Win32Data AccessprocesswithisADOassigned.NET a unique process identifier (PID), and may be independently
PartloadedFiveand- WebunloadedApplicationsby theandoperatingXML WebsystemServicesas necessary (as well as programmatically using Win32 API
Chcalls)pter. As18 you- ASPmay.NETbeWebaware,PagestheandProcessesW b Contabrolsof the Task Manager utility (activated via the ChapterCtrl+Shift+Esc19 - ASPkeystroke.NET Web combination)Applications allows you to view statistics regarding the set of processes running
on a given machine, including its PID and image name (Figure 10-1). (If you do not see a PID column,
Chapter 20 - XML W b Services
select the View | Select Columns menu and check the PID box.)
Index
List of Figures
List of Tables
Second Edition
ISBN:1590590554
with a brief overview of the
moves to key technical and
developers.
Table
C# and
Part
Chapter
Chapter
Part
Chapter
Figure 10-1: The Windows Task Manager
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Every Win32 process has at least one main "thread" that functions as the entry point for the application.
Chapter 6 - Interfaces and Collections
Formally speaking, the first thread created by a process' entry point is termed the primary thread. Simply
Chapter 7 - Callback Interfaces, Delegates, and Events
put, a thread is a specific path of execution within a Win32 process. Traditional Windows applications
Chapter 8 - Advanced C# Type Construction Techniques
define the WinMain() method as the application's entry point. On the other hand, console application
Part Three - Programming with .NET Assemblies
provides the main() method for the same purpose.
Chapter 9 - Understanding .NET Assemblies
ChapterProcesses10 -thatProcesses,containAppDomains,single primaryContexts,threadandof executionThreads are intrinsically "thread-safe," given the fact
that there is only one thread that can access the data in the application at a given time. However, a single-
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
threaded process (especially one that is GUI-based) will often appear a bit unresponsive to the user if this
Part Four - Leveraging the .NET Libraries
single thread is performing a complex operation (such as printing out a lengthy text file, performing an
Chapter 12 - Object Serialization and the .NET Remoting Layer
exotic calculation, or attempting to connect to a remote server thousands of miles away).
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Given this potential drawback of single-threaded applications, the Win32 API makes it is possible for the
Chapter 15 - Programming with Windows Forms Controls
primary thread to spawn additional secondary threads (also termed worker threads) in the background,
Chapter 16 - The System.IO Namespace
using a handful of Win32 API functions such as CreateThread(). Each thread (primary or secondary)
Chapter 17 - Data Access with ADO.NET
becomes a unique path of execution in the process and has concurrent access to all shared points of data.
Part Five - Web Applications and XML Web Services
ChapterAs you18may- ASPhave.NETguessed,Web Pagdevelopersand WebtypicallyControlscreate additional threads to help improve the program's
overall responsiveness. Multithreaded processes provide the illusion that numerous activities are
Chapter 19 - ASP.NET Web Applications
happening at more or less the same time.
Chapter 20 - XML Web Services
Index
For example, an application may spawn a worker thread to perform a labor-intensive unit of work (again,
List of Figures
such as printing a large text file). As this secondary thread is churning away, the main thread is still
List of Tables
responsive to user input, which gives the entire process the potential of delivering greater performance. However, this may not actually be the case: using too many threads in a single process can actually degrade performance, as the CPU must switch between the active threads in the process (which takes time).
In reality, it is always worth keeping in mind that multithreading is most commonly an illusion provided by the operating system. Machines that host a single CPU do not have the ability to literally handle multiple threads at the same exact time. Rather, a single CPU will execute one thread for a unit of time (called a time-slice) based on the thread's priority level. When a thread's time-slice is up, the existing thread is suspended to allow another thread to perform its business. For a thread to remember what was happening before it was kicked out of the way, each thread is given the ability to write to Thread Local Storage (TLS) and is provided with a separate call stack, as illustrated in Figure 10-2.
ISBN:1590590554
of the and
Table Figureof Contents10-2: The Win32 process / thread relationship
C# and the .NET Platform, Second Edition
Note The newest Intel CPUs have an ability called hyperthreading that allows a single CPU to handle
Introduction
multiple threads simultaneously under certain circumstances. See
Part One - Introducing C# and the .NET Platform
http://www.intel.com/info/hyperthreading for more details.
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
InteractingC#withand Processesthe .NET Platform,UnderSecondtheEdition.NET Platform
by Andrew Troelsen |
ISBN:1590590554 |
Although processes and threads are nothing new, the manner in which we interact with these primitives
Apress © 2003 (1200 pages)
under the .NET platform has changed quite a bit (for the better). To pave the way to understanding the
This comprehensive text starts with a brief overview of the
world of building C#multithreadedlangu ge andassemblies,then quicklylet'smovbegins tobykeycheckingt chnicaloutandhow processes have been altered to accommodate thearchitecturalneeds of theissuesCLRfor. .NET developers.
The System.Diagnostics namespace defines a number of types that allow you to programmatically interact
Tablewith ofprocessesContentsand various diagnostic-related types such as the system event log and performance C#countersa d the. For.NETthePlatform,purposesSecofndthisEditionchapter, we are only concerned with the process-centric types, defined in
Table 10-1.
Introduction
Part One - Introducing C# and the .NET Platform
Table 10-1: Select Members of the System.Diagnostics Namespace
Ch pter 1 - The Philosophy of .NET
|
|
|
|
|
|
|
|
|
Chapter 2 |
- Building C# Applications |
|
|
Meaning in Life |
|
|
|
Process-Centric Types of |
|
|
|
|
||
Part Two - The C# Programming Language |
|
|
|
||||
|
the System.Diagnostics |
|
|
|
|
||
Chapter 3 |
- C# Language Fundamentals |
|
|
|
|
||
|
Namespace |
|
|
|
|
||
|
Chapter 4 |
- Object-Oriented Programming |
|
with C# |
|
|
|
|
|
|
|
||||
|
ChapterProcess5 |
- Exceptions and Object LifetimeThe Process class provides access to local and remote |
|
|
|||
|
Chapter 6 |
- Interfaces and Collections |
processes and also allows you to programmatically start and |
|
|
||
|
Chapter 7 |
|
|
|
stop processes. |
|
|
|
- Callback Interfaces, Delegates, and Events |
|
|
||||
|
|
|
|
|
|
|
|
|
Chapter 8 |
- Advanced C# Type Construction Techniques |
|
|
|||
|
ProcessModule |
This type represents a module (*.dll or *.exe) that is loaded |
|
|
|||
Part Three - Programming with .NET Assemblies |
|
|
|||||
|
|
|
|
|
into a particular process. Understand that the ProcessModule |
|
|
Chapter 9 |
- Understanding .NET Assemblies |
|
|
||||
|
|
|
|
|
type can represent any module, COM-based, .NET-based, or |
|
|
Chapter 10 |
- Processes, AppDomains, Contexts, and Threads |
|
|
||||
|
|
|
|
|
traditional C-based binaries. |
|
|
|
|
|
|
|
|
|
|
|
Chapter 11 |
- Type Reflection, Late Binding, |
and Attribute-Based Programming |
|
|
||
|
ProcessModuleCollection |
|
Provides a strongly typed collection of ProcessModule |
|
|
||
Part Four - Leveraging the .NET Libraries |
|
objects. |
|
|
|||
|
|
|
|
|
|
|
|
|
Chapter 12 |
- Object Serialization and the |
|
.NET Remoting Layer |
|
|
|
|
ProcessStartInfo |
|
|
Specifies a set of values used when starting a process via the |
|
|
|
|
Chapter 13 |
- Building a Better Window |
|
(Introducing Windows Forms) |
|
|
|
|
Chapter 14 |
- A Better Painting Framework |
|
Process(GDI+) .Start() method. |
|
|
|
|
|
||||||
|
Chapter 15 |
- Programming with Windows |
|
Forms Controls |
|
|
|
|
ProcessThread |
|
|
Represents a thread within a given process. ProcessThread |
|
|
|
|
Chapter 16 |
- The System.IO Namespace |
|
|
is a type used to diagnose a process' thread set, and is not |
|
|
|
Chapter 17 |
- Data Access with ADO.NET |
|
|
used to spawn new threads of execution within a process. As |
|
|
Part Five - Web Applications and XML Web Services |
|
|
|||||
|
|
|
|
|
you will see later in this chapter, duties of this sort are the role |
|
|
Chapter 18 |
- ASP.NET Web Pages and Web Controls |
|
|
||||
|
|
|
|
|
of the types within the System.Threading namespace. |
|
|
|
Chapter 19 |
- ASP.NET Web Applications |
|
|
|
|
|
|
|
|
Provides a strongly typed collection of ProcessThread |
|
|
||
|
ProcessThreadCollection |
|
|
|
|
||
|
Chapter 20 |
- XML Web Services |
|
|
objects. |
|
|
Index |
|
|
|
|
|
||
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
List of Figures
The System.Diagnostics.Process type allows you to identify the running processes on a given machine
List of Tables
(local or remote). The Process class also provides members that allow you to programmatically start and terminate processes, establish a process' priority level, and obtain a list of active threads and/or loaded modules within a given process. Table 10-2 illustrates some (but not all) of the key members of System.Diagnostics.Process.
Table 10-2: Select Members of the Process Type
Member of
System.Diagnostic.Process
ExitCode
Meaning in Life
This property gets the value that the associated process specified when it terminated.
Do note that you will be required to handle the Exited event (for asynchronous notification) or call the WaitForExit() method (for synchronous notification) to obtain this value.
|
|
|
|
|
|
ExitTime |
C# and the .NET Platform,ThisSecondpropertyEditiongets the time stamp associated with the |
|
|||
|
by Andrew Troelsen |
|
|
process that has terminated (represented with a DateTime |
|
|
|
|
ISBN:1590590554 |
|
|
|
Apress © 2003 (1200 pages) |
|
|
type). |
|
|
|
|
|||
Handle |
This comprehensive text |
|
|
starts with a brief overview of the |
|
|
|
|
Returns the handle associated to the process by the OS. |
|
|
|
C# language and then |
|
quickly moves to key technical and |
|
|
|
|
|
|||
HandleCount |
architectural issues for |
|
.NET develop rs. |
|
|
|
|
|
Returns the number of handles opened by the process. |
|
Id
Table of Contents
C# and the .NET Platform, Second Edition
MachineName
Introduction
This property gets the process ID (PID) for the associated process.
This property gets the name of the computer the associated process is running on.
|
|
|
|
|
Part One - Introducing C# and the .NET Platform |
||||
|
MainModule |
Gets the ProcessModule type that represents the main |
||
Chapter 1 - The Philosophy of .NET |
module for a given process. |
|||
|
Chapter 2 |
- Building C# Applications |
|
|
|
|
|||
Part Two - The C# Programming Language |
|
MainWindowTitle gets the caption of the main window of |
||
|
MainWindowTitle |
|
||
Chapter 3 - C# Language Fundamentals |
|
the process (if the process does not have a main window, |
||
|
MainWindowHandle |
|
||
Chapter 4 |
- Object-Oriented Programming |
|
with C# |
|
|
|
|
|
you receive an empty string). MainWindowHandle gets the |
Chapter 5 - Exceptions and Object Lifetime |
|
underlying handle (represented via a System.IntPtr type) of |
||
Chapter 6 |
- Interfaces and Collections |
|
the associated window. If the process does not have a |
|
Chapter 7 - Callback Interfaces, Delegates, |
|
mainand Eventswindow, the IntPtr type is assigned the value |
||
Chapter 8 |
- Advanced C# Type Construction |
|
System.IntPtr.Zero.Techniques |
|
|
|
|
|
|
Part Three - Programming with .NET Assemblies
Modules Provides access to the strongly typed
Chapter 9 - Understanding .NET AssembliesProcessModuleCollection type, which represents the set of
Chapter 10 - Processes, AppDomains, Contexts, and Threads
modules (*.dll or *.exe) loaded within the current process.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
PartPriorityBoostEnabledFour - Leveraging the .NET Libraries |
Determines if the OS should temporarily boost the process |
||
|
|
|
if the main window has the focus. |
|
Chapter 12 - Object Serialization and the .NET Remoting Layer |
||
|
|
|
|
|
Chapter 13 - Building a Better Window (Introducing Windows Forms) |
||
|
PriorityClass |
Allows you to read or change the overall priority for the |
|
|
Chapter 14 |
- A Better Painting Framework (GDI+) |
|
|
|
|
associated process. |
|
|
|
|
|
Chapter 15 |
- Programming with Windows |
Forms Controls |
|
ProcessName |
This property gets the name of the process (which as you |
|
|
Chapter 16 |
- The System.IO Namespace |
would assume is the name of the application itself). |
|
Chapter 17 |
- Data Access with ADO.NET |
|
|
|
PartRespondingFive - Web Applications and XML Web ServicesThis property gets a value indicating whether the user
Chapter 18 - ASP.NET Web Pages and Web Continterfaceols of the process is responding (or not).
|
Chapter 19 - ASP.NET Web Applications |
|
This property gets the time that the associated process |
|
StartTime |
|
|
|
Chapter 20 - XML Web Services |
|
was started (via a DateTime type). |
Index |
|
||
|
|
||
|
|
||
ListThreadsof Figures |
|
This property gets the set of threads that are running in the |
|
List of Tables |
|
associated process (represented via an array of |
|
|
|
|
ProcessThread types). |
|
|
|
|
|
CloseMainWindow() |
|
Closes a process that has a user interface by sending a |
|
|
|
close message to its main window. |
|
|
|
|
|
GetCurrentProcess() |
|
This static method returns a new Process type that |
|
|
|
represents the currently active process. |
|
|
|
|
|
GetProcesses() |
|
This static method returns an array of new Process |
|
|
|
components running on a given machine. |
|
|
|
|
|
Kill() |
|
Immediately stops the associated process. |
|
|
|
|
|
Start() |
|
Starts a process. |
Enumerating Running Processes
To illustrate the process of manipulating Process types (pardon the redundancy), assume you have a C# |
|
C# and the .NET Platform, Second Edition |
|
console application named ProcessManipulator, which defines the following static helper method: |
|
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
public static void ListAllRunningProcesses()
This comprehensive text starts with a brief overview of the
{C# language and then quickly moves to key technical and
allrchitecturalprocessesissu s for .NET developers.
// Get the on the local machine.
Process[] runningProcs = Process.GetProcesses(".");
// Print out PID and name of each proc.
Table of Contents
foreach(Process p in runningProcs)
C# and the .NET Platform, Second Edition
{
Introduction string info = string.Format("-> PID: {0}\tName: {1}", |
||
Part One - Introducing C# and the .NET Platform |
||
|
|
p.Id, p.ProcessName); |
Chapter 1 |
- The Phil sophy of .NET |
|
Chapter }2 |
Console.WriteLine(info); |
|
- Building C# Applications |
||
Part TwoConsole- The C#.ProgrammWriteLinge("************************************\n");Language |
||
Chapter} |
3 |
- C# Language Fundamentals |
Chapter 4 |
- Object-Oriented Programming with C# |
|
Chapter 5 |
- Exceptions and Object Lifetime |
Notice how the static Process.GetProcesses() method returns an array of Process types that represent the
Chapter 6 - Interfaces and Collections
running processes on the target machine (the dot notation seen here represents the local computer).
Chapter 7 - Callback Interfaces, Delegates, and Events
ChaptOncer 8 - Advanced C# Type Construction Techniques
you have obtained the array of Process types, you are able to trigger any of the members seen in PartTableThree10--2Programming. Here, simplywithdump.NETtheAssembliesprocess identifier (PID) and the name of each process. Assuming the ChapterMain() method9 - Underhastandibeengupdated.NET Assembliesto call this helper function, you will see something like the output in Figure
10-3. |
|
Chapter 10 - Processes, AppDomains, Contexts, and Threads |
|
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming |
|
Part Four |
|
Chapter |
Remoting Layer |
Chapter |
Windows Forms) |
Chapter |
|
Chapter |
Controls |
Chapter |
|
Chapter
Part
Chapter
Chapter
Chapter
Index
List of
List ofFigureTables 10-3: Enumerating running processes
Investigating a Specific Process
In addition to obtaining a full and complete list of all running processes on a given machine, the static Process.GetProcessById() method allows you to obtain a single Process type via the associated PID. As you would hope, if you request access to a nonexistent process ID, an ArgumentException exception is thrown:
//If there is no process with the PID of 987, a
//runtime exception will be thrown.
int pID = 987;
Process theProc;
try
{ theProc = Process.GetProcessById(pID); }
catch // Generic catch for simplicitiy
C# and the .NET Platform, Second Edition
{ Console.WriteLine("-> Sorry...bad PID!"); }
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
Investigatingarchitectua Process'al issues forThread.NET developSetrs.
Now that you understand how to gain access to a Process type, you are able to programmatically Tableinvestigateof Contentsthe set of all threads currently alive in the process at hand. This set of threads is represented by
the strongly typed ProcessThreadCollection collection, which contains any number of individual
C# and the .NET Platform, Second Edition
ProcessThread types. To illustrate, assume the following additional static helper function has been added
Introduction
to your current application:
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET
Chapterpublic2 static- BuildingvoidC# ApplicationsEnumThreadsForPid(int pID)
Part{ Two - The C# Programming Language
Process theProc;
Chapter 3 - C# Language Fundamentals
try
Chapter 4 - Object-Oriented Programming with C#
{ theProc = Process.GetProcessById(pID); }
Chapter 5 - Exceptions and Object Lifetime
catch
Chapter 6 - Interfaces and Collections
{
Chapter 7 - Callback Interfaces, Delegates, and Events
Console.WriteLine("-> Sorry...bad PID!");
Chapter 8 - Advanced C# Type Construction Techniques
Console.WriteLine("************************************\n");
Part Three - Programming with .NET Assemblies
return;
Chapter 9 - Understanding .NET Assemblies
}
Chapter 10 - Processes, AppDomains, Contexts, and Threads
// List out stats for each thread in the specified process.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Console.WriteLine("Here are the thread IDs for: {0}",
Part Four - Leveraging the .NET Libraries
theProc.ProcessName);
Chapter 12 - Object Serialization and the .NET Remoting Layer
ProcessThreadCollection theThreads = theProc.Threads;
Chapter 13 - Building a Better Window (Introducing Windows Forms) foreach(ProcessThread pt in theThreads)
Chapter 14 - A Better Painting Framework (GDI+)
{
Chapter 15 - Programming with Windows Forms Controls string info =
Chapter 16 - The Systemstring.IO Namesp.Format("ce -> Thread ID: {0}\tStart Time {1}\tPriority {2}",
Chapter 17 - Data Accesspt.withId ADO, pt.NET.StartTime.ToShortTimeString(), pt.PriorityLevel);
Part Five - Web ApplicationsConsole.WriteLine(info);band XML Services
Chapter }18 - ASP.NET Web Pages and Web Controls
Console.WriteLine("************************************\n");
Chapter 19 - ASP.NET Web Applications
}
Chapter 20 - XML Web Services
Index
List of Figures
As you can see, the Threads property of the System.Diagnostics.Process type provides access to the
List of Tables
ProcessThreadCollection class. Here, we are printing out the assigned thread ID, start time, and priority level of each thread in the process specified by the client. Thus, if you update your program's Main() method to prompt the user for a PID to investigate:
Console.WriteLine("***** Enter PID of process to investigate *****");
Console.Write("PID: ");
string pID = Console.ReadLine();
int theProcID = int.Parse(pID);
EnumThreadsForPid(theProcID);
you would find output along the lines of the Figure 10-4.
ISBN:1590590554
of the
technical and
Table
C# and
Part
Chapter
Figure 10-4: Enumerating the threads within a running process
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
ChapterThe ProcessThread3 - C# LanguagetypeFundhas additionalmentals members of interest beyond Id, StartTime, and PriorityLevel. Table
Chapter10-3 documents4 - Objectsome-Ori ntedmembersProgrammingof interestwith. C#
Chapter 5 - Exceptions and Object Lifetime
ChTablepter 106 -3:- InterfacesSelect Membersand Collectionsof the ProcessThread Type
|
Chapter 7 |
- Callback Interfaces, Delegates, and Events |
|
Meaning in Life |
|
|
Member of |
|
|
||
|
Chapter 8 |
- Advanced C# Type Construction Techniques |
|
|
|
|
System.Diagnostics.ProcessThread |
|
|
|
|
Part Three - Programming with .NET Assemblies |
|
|
|
||
|
|
|
|||
ChapterBasePriority9 - Understanding .NET Assemblies |
|
Gets the base priority of the thread |
|
||
|
|
|
|
|
|
|
Chapter 10 |
- Processes, AppDomains, Contexts, and Threads |
|
||
|
CurrentPriority |
Gets the current priority of the thread |
|
||
|
Chapter 11 |
- Type Reflection, Late Binding, and Attribute- |
|
Based Programming |
|
|
|
|
|||
PartIdFour - Leveraging the .NET Libraries |
Gets the unique identifier of the thread |
|
|||
|
|
|
|
|
|
|
Chapter 12 |
- Object Serialization and the .NET Remoting |
|
Layer |
|
|
IdealProcessor |
|
Sets the preferred processor for this thread |
|
|
|
Chapter 13 |
- Building a Better Window (Introducing Windows Forms) |
|
||
|
|
|
|
to run on |
|
|
Chapter 14 |
- A Better Painting Framework (GDI+) |
|
|
|
|
|
|
|
||
|
ChapterPriorityLevel15 - Programming with Windows Forms Controls |
|
Gets or sets the priority level of the thread |
|
|
|
|
|
|
|
|
|
Chapter 16 |
- The System.IO Namespace |
|
Sets the processors on which the associated |
|
|
ProcessorAffinity |
|
|
||
|
Chapter 17 |
- Data Access with ADO.NET |
|
thread can run |
|
|
|
|
|
|
|
Part Five - Web Applications and XML Web Services
StartAddress
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
StartTime
List of Figures
List of Tables
ThreadState
TotalProcessorTime
WaitReason
Gets the memory address of the function that the operating system called that started this thread
Gets the time that the operating system started the thread
Gets the current state of this thread
Gets the total amount of time that this thread has spent using the processor
Gets the reason that the thread is waiting
Now before reading any further, be very aware that the ProcessThread type is not the entity used to create, suspend, or kill threads under the .NET platform. Rather, ProcessThread is a vehicle used to obtain diagnostic information for the active threads within a running process.
Investigating a Process' Module Set
Next up, let's check out how to iterate over the number of loaded modules that are hosted within a given process. Recall that a module is a generic name used to describe a given *.dll (or the *.exe itself) which is
hosted by a specific process. When you access the ProcessModuleCollection via the Process.Module
C# and the .NET Platform, Second Edition
property, you are able to enumerate over all modules in a process; .NET-based, COM-based, or traditional
by Andrew Troelsen |
ISBN:1590590554 |
C-based binaries. Ponder the following helper function: |
|
Apress © 2003 (1200 pages) |
|
This comprehensive text starts with a brief overview of the
public static void EnumModsForPid(int pID)
C# language and then quickly moves to key technical and
{architectural issues for .NET developers.
Process theProc; try
Table of {ContentstheProc = Process.GetProcessById(pID); }
catch
C# and the .NET Platform, Second Edition
{
Introduction
Console.WriteLine("-> Sorry...bad PID!");
Part One - Introducing C# and the .NET Platform
Console.WriteLine("************************************\n");
Chapter 1 - The Philosophy of .NET
return;
Chapter 2 - Building C# Applications
Part Two}- The C# Programming Language
Console.WriteLine("Here are the loaded modules for: {0}",
Chapter 3 - C# Language Fundamentals
theProc.ProcessName);
Chapter 4 - Object-Oriented Programming with C# try
Chapter 5 - Exceptions and Object Lifetime
{
Chapter 6 - Interfaces and Collections
ProcessModuleCollection theMods = theProc.Modules;
Chapter 7 - Callback Interfaces, Delegates, and Events foreach(ProcessModule pm in theMods)
Chapter 8 - Advanced C# Type Construction Techniques
{
Part Three - Programming with .NET Assemblies
string info = string.Format("-> Mod Name: {0}", pm.ModuleName);
Chapter 9 - Understanding .NET Assemblies
Console.WriteLine(info);
Chapter 10 - Processes, AppDomains, Contexts, and Threads
}
Chapter Console11 - Type Reflection, Late Binding, and Attribute-Based Programming
.WriteLine("************************************\n");
Part Four}- Leveraging the .NET Libraries
Chapter catch{Console12 - Object Serialization.WriteLine("Noand the .NET Remotingmods!");}Layer
Chapter} 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
To illustrate one possible invocation of this function, let's check out the loaded modules for the process
Chapter 16 - The System.IO Namespace
hosting your current console application (ProcessManipulator). To do so, run the application, identify the PID assigned to ProcessManipulator.exe, and pass this value to the EnumModsForPid() method (be sure to update your Main() method accordingly). Once you do, you may be surprised to see the list of *.dlls used for
a simple console application (atl.dll, mfc42u.dll, oleaut32.dll and so forth.) Figure 10-5 shows a test run.
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of
List of
Figure 10-5: Enumerating the loaded modules within a running process
C# and the .NET Platform, Second Edition
Starting and Killing Processes Programmatically
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
The final aspects of the System.Diagnostics.Process type examined here are the Start() and Kill() methods. As you can gatherThisbycomprehensivetheir names, thesetext startsmemberswith providea brief overviewa way toofprogrammaticallythe launch and terminate
C# language and then quickly moves to key technical and a process. For example:
architectural issues for .NET developers.
public static void StartAndKillProcess()
{
Table of Contents
// Launch Internet Explorer.
C# and the .NET Platform, Second Edition
Process ieProc = Process.Start("IExplore.exe",
Introduction
"www.intertech-inc.com");
Part One - Introducing C# and the .NET Platform
Console.Write("--> Hit enter to kill {0}...", ieProc.ProcessName);
Chapter 1 - The Philosophy of .NET
Console.ReadLine();
Chapter 2 - Building C# Applications
// Kill the iexplorer.exe process.
Part Two - The C# Programming Language
try { ieProc.Kill(); }
Chapter 3 - C# Language Fundamentals
catch{} // In case user already killed it...
Chapter 4 - Object-Oriented Programming with C#
}
Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections
ChapterThe static7 -ProcessCallback.Start()Interfacmethods, Delegates,has beenandoverloadedEvents a few times, however. At minimum you will need to
Chapterspecify8the-friendlyAdvancednameC# Typeof theConstructionprocess youTechniqueswish to launch (such as MS Internet Explorer). This example
PartmakesThreeuse- Programmingof variation withof the.NETStart()Assembliesmethod that allows you to specify any additional arguments to pass Chapterinto the9program's- Understandingentry point.NET(i.Assemblies., the Main() method).
Chapter 10 - Processes, AppDomains, Contexts, and Threads
The Start() method also allows you to pass in a System.Diagnostics.ProcessStartInfo type to specify additional bits of information regarding how a given process should come into life. Here is the formal
definition of ProcessStartInfo (see online Help for full details of this type):
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
public sealed class System.Diagnostics.ProcessStartInfo :
Chapter 14 - A Better Painting Framework (GDI+)
object
Chapter 15 - Programming with Windows Forms Controls
{
Chapter 16 - The System.IO Namespace
public |
ProcessStartInfo(); |
Chapter 17 - Data Access with ADO.NET |
|
public |
ProcessStartInfo(string fileName); |
Part Five - Web Applications and XML Web Services |
|
public |
ProcessStartInfo(string fileName, string arguments); |
Chapter 18 - ASP.NET Web Pages and Web Controls |
|
public |
string Arguments { get; set; } |
Chapter 19 - ASP.NET Web Applications |
|
public |
bool CreateNoWindow { get; set; } |
Chapter 20 - XML Web Services |
|
public |
StringDictionary EnvironmentVariables { get; } |
Index public |
bool ErrorDialog { get; set; } |
List of Figures |
IntPtr ErrorDialogParentHandle { get; set; } |
public |
|
List of Tables |
string FileName { get; set; } |
public |
|
public |
bool RedirectStandardError { get; set; } |
public |
bool RedirectStandardInput { get; set; } |
public |
bool RedirectStandardOutput { get; set; } |
public |
bool UseShellExecute { get; set; } |
public |
string Verb { get; set; } |
public |
string[] Verbs { get; } |
public |
ProcessWindowStyle WindowStyle { get; set; } |
public |
string WorkingDirectory { get; set; } |
public |
virtual bool Equals(object obj); |
public |
virtual int GetHashCode(); |
public |
Type GetType(); |
public |
virtual string ToString(); |
} |
|
Regardless of which version of the Process.Start() method you invoke, do note that you are returned a
C# and the .NET Platform, Second Edition
reference to the newly activated process. When you wish to terminate the process, simply call the instance
by Andrew Troelsen |
ISBN:1590590554 |
level Kill() method. |
|
Apress © 2003 (1200 pages) |
|
SOURCE ThisThecomprehensiveProcessManipulatortext startsapplicationwith a briefisoverviewincludedofunderthe the Chapter 10 subdirectory.
CODE C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents
C# and the .NET Platform, Second Edition
Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
UnderstandingC# andthet .SystemNET Platform,.AppDomainSecond Edit on Type
by Andrew Troelsen |
ISBN:1590590554 |
Now that you understand how to interact with a Win32 process from managed code, we need to examine more
Apress © 2003 (1200 pages)
closely the new (but related) concept of a .NET applicationdomain. As I mentioned briefly in the introduction,
This comprehensive text starts with a brief overview of the
unlike a traditionalC#(nonla guage-.NET)andWin32then*.quicklyexe application,moves to key.NETtechnicalassembliesand are hosted in a logical partition within aprocess termedarchitecturan applicationl issuesdomainfor .NET(akadevelopersAppDomain). and many application domains can be hosted inside a single OS process. This additional subdivision of a traditional Win32 process offers several benefits, some of which are:
Table of Contents
C#andAppDomainsthe .NET Platform,are a keySecondaspectEditionof the OS-neutral nature of the .NET platform, given that this logical division
abstracts away the differences in how an underlying operating system represents a loaded executable.
Introduction
Part One - Introducing C# and the .NET Platform
AppDomains are far less expensive in terms of processing power and memory than a full blown process
Chapter 1 - The Philosophy of .NET
(for example, the CLR is able to load and unload application domains much quicker than a formal
Chapter 2 - Building C# Applications process).
Part Two - The C# Programming Language
Chapter 3 |
- C# Language Fundam ntals |
AppDomains provide a deeper level of isolation for hosting a loaded application. If one AppDomain within a |
|
Chapter 4 |
- Object-Oriented Pro ramming w th C# |
process fails, the remaining AppDomains remain functional.
Chapter 5 - Exceptions and Object Lifetime
As suggested in the previous hit-list, a single process can host any number of AppDomains, each of which is
Chapter 6 - Interfaces and Collections
fully and completely isolated from other AppDomains within this process (or any other process). Given this
Chapter 7 - Callback Interfaces, Delegates, and Events
factoid, be very aware that applications that run in unique AppDomains are unable to share any information of
Chapter 8 - Advanced C# Type Construction Techniques
any kind (global variables or static fields) unless they make use of the .NET Remoting protocol (examined in
Part Three - Programming with .NET Assemblies
Chapter 12) to marshal the data.
Chapter 9 |
- |
Understanding .NET Assemblies |
|
Chapter 10 |
- Processes, AppDomains, Contexts, and Threads |
|
|
Note In some respects, .NET application domains are reminiscent of the "apartment" architecture of classi |
|||
Chapter 11 |
- Type Reflection, Late Binding, and Attribute-B sed Programming |
||
|
COM. Of course, .NET AppDomains are managed types whereas the COM apartment architecture is |
||
Part Four - Leveraging the .NET Libraries |
|
||
|
built on an unmanaged (and hideously complex) structure. |
|
|
Chapter 12 |
- Object Serialization and the .NET Remoting Layer |
|
|
ChapterUnderstand13 - Buildingthat whilea Bettera singleWindowprocess(Introducingmay hostWindowsmultiple AppDomains,Forms) |
this is not always the case. At the very |
least an OS process will host what is termed the default application domain. This specific application domain is
Chapter 14 - A Better Painting Framework (GDI+)
automatically created by the CLR at the time the process launches. After this point, the CLR creates additional
Chapter 15 - Programming with Windows Forms Controls
application domains on an as-needed basis. If the need should arise (which it most likely will not for a majority
Chapter 16 - The System.IO Namespace
of your .NET endeavors), you are also able to programmatically create application domains at runtime within a
Chapter 17 - Data Access with ADO.NET
given process using static methods of the System.AppDomain class. This class is also useful for low-level
Part Five - Web Applications and XML Web Services
control of application domains. Key members of this class are shown in Table 10-4.
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Table 10-4: Select Members of AppDomain
Chapter 20 - XML Web Services
IndexAppDomain |
Meaning in Life |
|
ListMemberof Figures |
|
|
|
|
|
List of Tables |
This static method creates a new AppDomain in the current process. |
|
|
CreateDomain() |
|
|
|
Understand that the CLR will create new application domains as necessary, |
|
|
and thus the chance of you absolutely needing to call this member is slim to |
|
|
none (unless you happen to be building a custom CLR host). |
|
|
|
|
GetCurrentThreadId() |
This static method returns the ID of the active thread in the current |
|
|
application domain. |
|
|
|
|
Unload() |
Another static method that allows you to unload a specified AppDomain |
|
|
within a given process. |
|
|
|
|
BaseDirectory |
This property returns the base directory that the assembly resolver used to |
|
|
probe for dependent assemblies. |
|
|
|
|
CreateInstance() |
Creates an instance of a specified type defined in a specified assembly file. |
|
|
|
|
ExecuteAssembly() |
Executes an assembly within an application domain, given its file name. |
|
|
|
|
|
|
|
|
GetAssemblies()C# and |
theGets.NETthePlatform,set of .NETSecondassembliesEditionthat have been loaded into this application |
|
|||
|
|
by Andrew |
|
domain. Unlike the Process type, the GetAssemblies() method will only |
|
|
|
|
|
Troelsen |
ISBN:1590590554 |
|
|
|
|
Apress © |
|
return the list of true-blue .NET binaries. COM-based or C-based binaries are |
|
|
|
|
2003 (1200 pages) |
|
|
||
|
|
|
|
ignored. |
|
|
|
|
This comprehensive text starts with a brief overview of the |
|
|||
|
|
|
|
|
|
|
|
Load() |
C# language and then quickly moves to key technical and |
|
|||
|
|
|
Used to dynamically load an assembly into the current application domain. |
|
||
|
|
architectural |
issues for .NET developers. |
|
|
In addition, the AppDomain type also defines a small set of events that correspond to various aspects of an
Table of Contents
application domain's life-cycle (Table 10-5).
C# and the .NET Platform, Second Edition
Introduction
Table 10-5: Events of the AppDomain Type
Part One - Introducing C# and the .NET Platform
ChaptEventsr 1 |
-ofThe Philosophy of .NET |
|
Meaning in Life |
||||
ChapterSystem.AppDomain2 - Building C# Applications |
|
|
|
|
|||
|
|
|
|
|
|
||
Part Two - The C# Programming Language |
|
|
|||||
|
AssemblyLoad |
|
Occurs when an assembly is loaded |
|
|
||
|
Chapter |
3 |
- C# Language Fundamentals |
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|||
|
ChapterAssemblyResolve4 - Object-Oriented ProgrammingOccurswithwhenC# the resolution of an assembly fails |
|
|
||||
|
|
|
|
|
|
|
|
|
Chapter |
5 |
- Exceptions and Object |
|
Lifetime |
|
|
|
DomainUnload |
|
Occurs when an AppDomain is about to be unloaded |
|
|
||
|
Chapter |
6 |
- Interfaces and Collections |
|
|
|
|
|
|
|
|
|
|||
|
|
|
|
|
|||
|
ChapterProcessExit7 - Callback Interfaces, Delegates,OccursandonEventsthe default application domain when the default |
|
|
||||
|
Chapter |
8 |
- Advanced C# Type ConstructionapplicationTechniquesdomain's parent process exits |
|
|
||
|
|
|
|
|
|
||
Part Three - Programming with .NET |
|
Assemblies |
|
|
|||
|
ResourceResolve |
|
Occurs when the resolution of a resource fails |
|
|
||
|
Chapter |
9 |
- Understanding .NET Assemblies |
|
|
||
|
|
|
|||||
|
ChapterTypeResolve10 - Processes, AppDomains, Contexts,Occurs whenand Tthereadsresolution of a type fails |
|
|
||||
|
|
|
|
|
|
|
|
|
Chapter |
11 |
- Type Reflection, Late Binding, and Attribute-Based Programming |
|
|
||
|
UnhandledException |
|
Occurs when an exception is not caught by an event handler |
|
|
||
Part Four - Leveraging the .NET Libraries |
|
||||||
Chapter |
12 |
- Object Serialization and the .NET Remoting Layer |
|||||
Chapter |
13 |
- Building a Better Window (Introducing Windows Forms) |
|||||
ChapterFun |
14with- A BetterAppDomainsPainting Framework (GDI+) |
||||||
Chapter |
15 |
- Programming with Windows Forms Controls |
|||||
To illustrate how to interact with .NET application domains programmatically, assume you have a new C# |
|||||||
Chapter |
16 |
- The System.IO Namespace |
|||||
console application named AppDomainManipulator. The static PrintAllAssembliesInAppDomain() helper |
|||||||
Chapter |
17 |
- Data Access with ADO.NET |
|||||
method makes use of AppDomain.GetAssemblies() to obtain a list of all .NET binaries hosted within the |
|||||||
Part Five - Web Applications and XML Web Services |
|||||||
application domain in question. |
|
|
|
|
|||
Chapter |
18 |
- ASP.NET Web Pages and Web Controls |
ChapterThis list19is -representedASP.NET WebbyApplicationsan array of System.Reflection.Assembly types, and thus we are required to use the
System.Reflection namespace (full details of this namespace and the Assembly type are seen in Chapter 11).
Chapt r 20 - XML Web Services
Once we obtain the list of loaded assemblies, we iterate over the array and print out the friendly name and
Index
version of each module:
List of Figures
List of Tables
using System.Reflection; // For the Assembly type.
...
public static void PrintAllAssembliesInAppDomain(AppDomain ad)
{
Assembly[] loadedAssemblies = ad.GetAssemblies(); Console.WriteLine("***** Here are the assemblies loaded in {0} *****\n",
ad.FriendlyName);
foreach(Assembly a in loadedAssemblies)
{
Console.WriteLine("-> Name: {0}", a.GetName().Name);
Console.WriteLine("-> Version: {0}\n", a.GetName().Version);
}
}
Now assume you have updated the Main() method to obtain a reference to the current application domain
C# and the .NET Platform, Second Edition
before invoking PrintAllAssembliesInAppDomain(), using the AppDomain.CurrentDomain property. To make
by Andrew Troelsen ISBN:1590590554
things a bit more interesting, notice that the Main() method launches a message box to force the assembly
Apress © 2003 (1200 pages)
resolver to load the System.Windows.Forms.dll and System.dll assemblies (so be sure to set a reference to
This comprehensive text starts with a briefappropriately):ove view of the these assemblies and update your "using" statements
C# language and then quickly moves to key technical and
architectural issues for .NET developers.
public static int Main(string[] args)
{
Table of Consoletents.WriteLine("***** The Amazing AppDomain app *****\n");
// Get info for current AppDomain.
C# and the .NET Platform, Second Edition
AppDomain defaultAD= AppDomain.CurrentDomain;
Introduction
MessageBox.Show("This call loaded System.Windows.Forms.dll and System.dll")
Part One - Introducing C# and the .NET Platform
PrintAllAssembliesInAppDomain(defaultAD);
Chapter 1 - The Philosophy of .NET
Chapter return2 - Building0; C# Applications |
|
Part} Two - The C# Programming Language |
|
Chapter 3 - C# Language Fundamentals |
|
Chapter 4 - Object-Oriented Programming with C# |
|
Figure 10-6 shows the output. |
|
Chapter 5 - Exceptions and Object Lifetime |
|
Chapter 6 - Interfaces and Collections |
|
Chapter |
|
Chapter |
|
Part |
|
Chapter |
|
Chapter |
|
Chapter |
Programming |
Part |
|
Chapter
Chapter
ChapterFigure14 - 10A Better-6: EnumeratingPainting Frameworkassemblies(GDI+)within a given app domain (within a given process)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
ChapterProgrammatically17 - Data Access withCreatingADO.NET New AppDomains
Part Five - Web Applications and XML Web Services
ChapterRecall 18that-aASPsingle.NETprocessWeb Pagesis capablend WebofControlshosting multiple AppDomains. While it is true that you will seldom (if
ever) need to manually create AppDomains directly (unless you happen to be creating a custom host for the
Chapter 19 - ASP.NET Web Applications
CLR), you are able to do so via the static CreateDomain() method. As you would guess, this method has been
Chapter 20 - XML Web Services
overloaded a number of times. At minimum you will simply specify the friendly name of the new application
Index
domain as seen here:
List of Figures
List of Tables
public static int Main(string[] args)
{
...
// Make a new AppDomain in the current process.
AppDomain anotherAD = AppDomain.CreateDomain("SecondAppDomain");
PrintAllAssembliesInAppDomain(anotherAD);
return 0;
}
Now, if you run the application again (Figure 10-7), notice that the System.Windows.Forms.dll and System.dll assemblies are only loaded within the default application domain! This may seem counterintuitive if you have a background in traditional Win32 (as you might suspect that both application domains have access to the same assembly set). Recall, however, that an assembly loads into an applicationdomain, not directly into the process itself.
ISBN:1590590554
of the
and
Table
C# and
Part
ChapterFigure1 - 10The-7:PhilosophyA single processof .NET with two application domains
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
Next, notice how the SecondAppDomain application domain automatically contains its own copy of mscorlib.dll
Chapter 3 - C# Language Fundamentals
as this key assembly is automatically loaded by the CLR for each and every application domain. This begs the
Chapter 4 - Object-Oriented Programming with C#
question, "How can I programmatically load an assembly into an application domain?" Answer? The
Chapter 5 - Exceptions and Object Lifetime
AppDomain.Load() method (or alternatively, AppDomain.ExecuteAssembly()). I'll hold off on this topic until I
Chapter 6 - Interfaces and Collections
discuss the process of dynamically loading assemblies in Chapter 11 during our examination of .NET reflection
Chapter 7 - Callback Interfaces, Delegates, and Events
services.
Chapter 8 - Advanced C# Type Construction Techniques
To solidify the relationship between processes, application domains, and assemblies, Figure 10-8 diagrams the
Part Three - Programming with .NET Assemblies
internal composition of the AppDomainManipulator.exe process you have just constructed.
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter |
Programming |
Part
Chapter
Chapter
Chapter
Chapter
Chapter
Chapter
Part
Chapter
Chapter
Chapter
Index
List ofFigureFig s10-8: The AppDomainManipulator.exe process under the hood
List of Tables
Programmatically Unloading AppDomains (and Hooking into Events)
It is important to point out that the CLR does not permit unloading individual .NET assemblies. However, using the AppDomain.Unload() method you are able to selectively unload a given application domain from its hosting process. When you do so, the application domain will unload each assembly in turn.
Recall that the AppDomain type defines a small set of events, one of which is DomainUnload. This is fired whe a (non-default) AppDomain is unloaded from the containing process. Another event of interest is the ProcessExit event, which is fired when the default application domain is unloaded from the process (which obviously entails the termination of the process itself). Thus, if you wish to programmatically unload anotherAD from the AppDomainManipulator.exe process, and be notified when the application domain is torn down, you are able to write the following event logic:
public static void anotherAD_DomainUnload(object sender, EventArgs e)
{ Console.WriteLine("***** Unloaded anotherAD! *****\n"); }
C# and the .NET Platform, Second Edition
...
by Andrew Troelsen |
ISBN:1590590554 |
// Hook into DomainUnload event. |
|
Apress © 2003 (1200 pages) |
|
anotherAD.DomainUnload += |
|
This comprehensive text starts with a brief overview of the new EventHandler(anotherAD_DomainUnload);
C# language and then quickly moves to key technical and
// Now unload anotherAD.
architectural issues for .NET developers.
AppDomain.Unload(anotherAD);
Table of Contents
If you wish to be notified when the default AppDomain is unloaded, modify your application to support the
C# and the .NET Platform, Second Edition following event logic:
Introduction
Part One - Introducing C# and the .NET Platform
private static void defaultAD_ProcessExit(object sender, EventArgs e)
Chapter 1 - The Philosophy of .NET
{ Console.WriteLine("***** Unloaded defaultAD! *****\n"); }
Chapter 2 - Building C# Applications
...
Part Two - The C# Programming Language
defaultAD.ProcessExit +=new EventHandler(defaultAD_ProcessExit);
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
ChapterSOURCE6 - InterfacesTheandAppDomainManipulatorCollections project is included under the Chapter 10 subdirectory.
ChapterCODE7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
UnderstandingC# andContextthe .NET Platform,(or HowSecondLowEditionCan You Go?)
by Andrew Troelsen |
ISBN:1590590554 |
As you have just seen, AppDomains are logical partitions within a process used to host .NET assemblies. A giv
Apress © 2003 (1200 pages)
application domain may be further subdivided into numerous context boundaries. In a nutshell, a .NET context
This comprehensive text starts with a brief overview of the
provides a way forC#alasingleuageAppDomainand then quicklyto partitionm ves.NETto keyobjectste hnicthatl andhave similar execution requirements. Usin context, the CLRarchitecis able touralensurei suesthatfor objects.NET developersthat have. special runtime requirements are handled appropriate and in a consistent manner by intercepting method invocations into and out of a given context. This layer of interception allows CLR to adjust the current method invocation to conform to the contextual settings of a given
Table of Contents
C#Justandasthea process.NET Platform,definesSeconda defaultEditionAppDomain, every application domain has a default context. This default co
(sometimes referred to as context 0, given that it is always the first context created within an application domain
Introduction
used to group together .NET objects that have no specific or unique contextual needs. As you may expect, a va
Part One - Introducing C# and the .NET Platform
majority of your .NET class types will be loaded into context 0. If the CLR determines a newly created object ha
Chapter 1 - The Philosophy of .NET
special needs, a new context boundary is created within the hosting application domain. Figure 10-9 illustrates t
Chapter 2 - Building C# Applications
process, AppDomain, context relationship.
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
Chapter
Chapter
Chapter
Chapter
Chapter
Part
Chapter |
|
Chapter |
|
Chapter |
Based Programming |
Part |
|
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure 10-9: Processes, application domains, and context boundaries
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
ChapterContext15 - Programming-Agile andwithContextWindows Forms-BoundCo trolsTypes
Chapter 16 - The System.IO Namespace
Chapter.NET types17 - thatDatadoAccessnot demandwith ADOany.NETspecial contextual treatment are termed context-agile objects. These objec PartcanFivebe accessed- Web Applicatiofrom anywheres and XMLwithinWebtheServiceshosting AppDomain without interfering with the object's runtime
requirements. Building context-agile objects is a no-brainer, given that you simply do nothing (specifically, you d
Chapter 18 - ASP.NET Web Pages and Web Controls
adorn the type with any contextual attributes and do not derive from the System.ContextBoundObject base clas
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index// A context-agile object is loaded into context 0.
public class IAmAContextAgileClassType{}
List of F gures
List of Tables
On the other hand, objects that do demand contextual allocation are termed context-bound objects, and must derive from the System.ContextBoundObject base class. This base class solidifies the fact that the object in question can only function appropriately within the context in which it was created.
In addition to deriving from System.ContextBoundObject, a context-sensitive type will also be adorned with a sp category of .NET attributes termed (not surprisingly) context attributes. All context attributes derive from the System.Runtime.Remoting.Contexts.ContextAttribute base class, which is defined as follows (note this class typ implements two context-centric interfaces, IContextAttribute and IContextProperty):
public class System.Runtime.Remoting.Contexts.ContextAttribute : Attribute, System.Runtime.Remoting.Contexts.IContextAttribute, System.Runtime.Remoting.Contexts.IContextProperty
{
public ContextAttribute(string name);
public string Name { virtual get; }
public |
C# and the .NET Platform, Second Edition |
|
object TypeId { virtual get; } |
ISBN:1590590554 |
|
public |
by Andrew Troelsen |
|
virtual bool Equals(object o); |
|
Apress © 2003 (1200 pages)
public virtual void Freeze(System.Runtime.Remoting.Contexts.Context newConte
This comprehensive text starts with a brief overview of the public virtual int GetHashCode();
C# language and then quickly moves to key technical and public virtual void GetPropertiesForNewContext(
architectural issues for .NET developers.
System.Runtime.Remoting.Activation.IConstructionCallMessage ctorMsg); public Type GetType();
public virtual bool IsContextOK(
Table of Contents
System.Runtime.Remoting.Contexts.Context ctx,
C# and the .NET Platform, Second Edition
System.Runtime.Remoting.Activation.IConstructionCallMessage ctorMsg);
Introduction
public virtual bool IsDefaultAttribute();
Part One - Introducing C# and the .NET Platform
public virtual bool IsNewContextOK(
Chapter 1 - The Philosophy of .NET
System.Runtime.Remoting.Contexts.Context newCtx);
Chapter 2 - Building C# Applications
public virtual bool Match(object obj);
Part Two - The C# Programming Language
public virtual string ToString();
Chapter 3 - C# Language Fundamentals
}
Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime
ChapterThe .NET6 -baseInterfacesclass librariesand Collectionsdefine numerous context attributes that describe specific runtime requirements (s
as thread synchronization and URL activation). Given the role of .NET context, it should stand to reason that if a
Chapter 7 - Callback Interfaces, Delegates, and Events
context-bound object were to somehow end up in an incompatible context, bad things are guaranteed to occur
Chapter 8 - Advanced C# Type Construction Techniques
the most inopportune times.
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
ChaptCreatingr 10 - Processes,a ContextAppDomains,-BoundContexts,Objectand Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
So, what sort of bad things might occur if a context-bound object is placed into an incompatible context? The
Part Four - Leveraging the .NET Libraries
answer depends on the object's advertised contextual settings. Assume for example that you wish to define a .N
Chapter 12 - Object Serialization and the .NET Remoting Layer
type that is automatically thread-safe in nature, even though you have not hard-coded thread-safe-centric logic
Chapter 13 - Building a Better Window (Introducing Windows Forms)
within the method implementations. To do so, you may apply the
Chapter 14 - A Better Painting Framework (GDI+)
System.Runtime.Remoting.Contexts.SynchronizationAttribute attribute as follows:
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
using System.Runtime.Remoting.Contexts;
Chapter 17 - Data Access with ADO.NET
...
Part Five - Web Applications and XML Web Services
// This context-bound type will only be loaded into a
Chapter 18 - ASP.NET Web Pages and Web Controls
// synchronized (and hence, thread safe) context.
Chapter 19 - ASP.NET Web Applications
[Synchronization]
Chapter 20 - XML Web Services
public class MyThreadSafeObject : ContextBoundObject
Index
{}
List of Figures
List of Tables
As you will see in greater detail later in this chapter, classes that are attributed with the [Synchronization] attribu are loaded into a thread-safe context. Given the special contextual needs of the MyThreadSafeObject class typ imagine the problems that would occur if an allocated object were moved from a synchronized context into a nonsynchronized context. The object is suddenly no longer thread-safe and thus becomes a candidate for mas data corruption, as numerous threads are attempting to interact with the (now thread-volatile) reference object. is obviously a huge problem, given that the code base has not specifically wrapped thread-sensitive resources hard-coded synchronization logic.
Placing Context in Context
Now, the good news is that you do not have to concern yourself with the act of ensuring that your context-bound objects are loaded into the correct contextual setting. The .NET runtime will read the assembly metadata when constructing the type, and build a new context within the current application domain when necessary.
To be honest, the notion of .NET context is an extremely low-level facility of the CLR. So much so, that a key
context-centric namespace, System.Runtime.Remoting.Context, only formally lists the SynchronizationAttribute
C# and the .NET Platform, Second Edition
class type within online Help (as of .NET version 1.1). The remaining members are considered usable only by t
by Andrew Troelsen ISBN:1590590554
CLR, and are intended to be ignored (which you should do, given that many members of this namespace are
Apress © 2003 (1200 pages)
subject to change in future releases of .NET).
This comprehensive text starts with a brief overview of the
Nevertheless, it isC#possiblelanguageto makeand thenusequicklyof thesemoveshandsto -keyoff types,technicalsimplyand as an academic endeavor. Thus, by w
architectural issues for .NET developers.
a friendly heads-up, understand that the following example is purely illustrative in nature. As a .NET programm you can safely ignore these low-level primitives in 99.99 percent of your applications. If you wish to see the form
definition of the any of the following context-centric types, make use of the wincv.exe utility.
Table of Contents
C# andNotetheCOM+.NET Platform,developersSecondareEditionalready aware of the notion of context. Using COM IDL attributes and the
IntroductionComponent Services utility, developers are able to establish contextual settings for a given COM+ typ
Part One - IntrodAlthoughcing.NETC# andtheCOM+.NETbothPlatformmake use of contextual boundaries, understand that the underlying
Chapter 1 implementations- The Philosophy of .bothNET systems are not the same and cannot be treated identically.
Chapter 2 - Building C# Applications
PartFunTwowith- The C#ContextProgramming Language
Chapter 3 - C# Language Fundamentals
ChaptTo begin,r 4 assume- Object-youOrientedhaveProgrammingnew consolewithapplicationC# named ContextManipulator. This application defines two
Chapcontextr 5-agile- Exceptionstypes andandsingleObj ctcontextLifetime-bound type:
Chapter 6 |
- Interfaces and Collections |
Chapter 7 |
- Callback In erfaces, Delegates, and Events |
using System.Runtime.Remoting.Contexts; // For Context type. |
|
Chapter 8 |
- Advanced C# Type Constructi n Techniques |
using System.Threading; // For Thread type.
Part...Three - Programming with .NET Assemblies
Chapter// These9 - Understandingclasses have.NETnoAssembliesspecial contextual
Chapter// needs10 - Processes,and willAppDomains,be loadedContexts,into andtheThreads
// default context of the app domain.
Chapter 11 - Type Refl ction, Late Binding, and Attribute-Based Programming
public class NoSpecialContextClass
Part Four - Leveraging the .NET Libraries
{
Chapter 12 - Object Serialization and the .NET Remoting Layer
public NoSpecialContextClass()
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter{14 - A Better Painting Framework (GDI+)
// Get context information and print out context ID.
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
foreach(IContextProperty itfCtxProp in ctx.ContextProperties)
Part Five - Web Applications and XML Web Services
Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name);
Chapter 18 - ASP.NET Web Pages and Web Controls
}
Chapter 19 - ASP.NET Web Applications
}
Chapter 20 - XML Web Services
public class NoSpecialContextClass2
Index
{
List of Figures
public NoSpecialContextClass2()
List of Tables
{
// Get context information and print out context ID.
Context ctx = Thread.CurrentContext;
Console.WriteLine("Info about context {0}", ctx.ContextID);
foreach(IContextProperty itfCtxProp in ctx.ContextProperties)
Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name);
}
}
//This class demands to be loaded in
//a synchronization context.
//RECALL! All context-bound types must derive from
//System.ContextBoundObject.
[Synchronization]
public class SynchContextClass : ContextBoundObject
{
public SynchContextClass()
{ |
C# and the .NET Platform, Second Edition |
|
out context ID. |
|
// Get context information and print |
||
|
by Andrew Troelsen |
ISBN:1590590554 |
|
|
Context ctx = Thread.CurrentContext; |
|
Apress © 2003 (1200 pages) ContextID
Console.WriteLine("Info about context {0}", ctx. );
foreach(IContextPropertyThis comprehensive text star s witfCtxPropth a brief overview of the ContextProperties in ctx. )
C# language and then quickly moves to key technical and
Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name); architectural issues for .NET developers.
}
}
Table of Contents
C# and the .NET Platform, Second Edition
Notice that each of the class constructors obtains a System.Runtime.Remoting.Contexts.Context type from the
Introduction
current thread of execution, via the static Thread.CurrentContext property. Using this type, you are able to print
Part One - Introducing C# and the .NET Platform
statistics about the contextual boundary, such as its assigned ID, as well as a set of descriptors obtained via the
Chapter 1 - The Philosophy of .NET
Context.ContextProperties property. This instance-level property returns a (very) low-level interface named
Chapter 2 - Building C# Applications
IContextProperty, which exposes each descriptor through the Name property.
Part Two - The C# Programming Language
Now, assume Main() has been updated to allocate an instance of each class type. As the objects come to life, t
Chapter 3 - C# Language Fundamentals
class constructors will dump out various bits of context-centric information (Figure 10-10):
Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime Chapterstatic6 void- InterfacesMain(string[]and Collectionsargs)
{
Chapter 7 - Callback Interfaces, Delegates, and Events
Console.WriteLine("***** The Amazing Context Application *****\n");
Chapter 8 - Advanced C# Type Construction Techniques
// Make each class type and print contextual info.
Part Three - Programming with .NET Assemblies
NoSpecialContextClass noBigDealObj = new NoSpecialContextClass();
Chapter 9 - Understanding .NET Assemblies
Console.WriteLine();
Chapter 10 - Processes, AppDomains, Contexts, and Threads
NoSpecialContextClass2 noBigDealObj2 = new NoSpecialContextClass2();
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Console.WriteLine();
Part Four - Leveraging the .NET Libraries
SynchContextClass synchObj = new SynchContextClass();
Chapter 12 - Object Serialization and the .NET Remoting Layer
Console.WriteLine();
Chapter 13 - Building a Better Window (Introducing Windows Forms)
}
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Chapter
Part
Chapter
Chapter
Chapter
Index
List of
List of
Figure 10-10: Investigating an object's context
Given that the NoSpecialContextClass and NoSpecialContextClass2 types have not been qualified with a speci context attribute, the CLR will have both loaded into context 0 (i.e., the default context). However, the SynchContextClass type is loaded into a unique contextual boundary within the current application domain, give fact that this context-bound type was adorned with the [Synchronization] attribute.
SOURCE The ContextManipulator project is included under the Chapter 10 subdirectory.
CODE
SummarizingC# andProcesses,the .NET Platform,AppDomains,Sec nd Editionand Context
by Andrew Troelsen |
ISBN:1590590554 |
So then, at this point in the game you have seen how the .NET runtime has altered the composition of a
Apress © 2003 (1200 pages)
traditional Win32 process to function within the common language runtime (CLR). To summarize the key
This comprehensive text starts with a brief overview of the points, rememberC#thelanguagefollowing:and then quickly moves to key technical and
architectural issues for .NET developers.
A .NET process hosts one to many application domains. Each AppDomain is able to host any number of related .NET assemblies, and may be independently loaded and unloaded by the CLR (or
Table programmaticallyof Contents via the System.AppDomain type).
C# and the .NET Platform, Second Edition
A given AppDomain consists of one to many contexts. Using a context, the CLR is able to group
Introduction
special needs objects into a logical container, to ensure that their runtime requirements are honored.
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET
If the previous pages have seemed to be a bit too low-level for your liking, fear not. For the most part, the
Chapter 2 - Building C# Applications
.NET runtime automatically deals with the details of processes, application domains, and contexts on your
Part Two - The C# Programming Language
behalf. However, this background discussion has provided a solid foundation regarding how the CLR
Chapter 3 - C# Language Fundamentals
creates, processes, and destroys specific threads of execution (as well as increased your understanding of
Chaptsomerunderlying4 - ObjectCLR-Orientedconcepts)Programming. with C#
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
The Process/AppDomain/Context/ThreadC# and the .NET Platform, S cond Edition Relationship
by Andrew Troelsen |
ISBN:1590590554 |
As mentioned at the opening of this chapter, a thread is a path of execution within a loaded application.
Apress © 2003 (1200 pages)
While many .NET applications can live happy and productive single-threaded lives, the primary thread may
This comprehensive text starts with a brief overview of the
spawn secondaryC#threadslanguageof executionand then quicklyto performmovesadditionalto key technicalunits of workand . In just a moment, you will be introduced to thearchitecturalSystem.Threadingissues fornamespace,.NET developerswhich. defines numerous types used to create multithreaded .NET applications. First however, we need to check out exactly "where" a thread lives within a .NET process.
Table of Contents
C#Theandfirstthething.NETyouPlatform,must understandSecond Editionis that under the .NET platform, there is not a direct one-to-one Introducticorrelation between application domains and threads. In fact, a given AppDomain can have numerous
threads executing within it at any given time. Furthermore, a particular thread is not confined to a single
Part One - Introducing C# and the .NET Platform
application domain during its lifetime. Threads are free to cross application domain boundaries as the
Chapter 1 - The Philosophy of .NET
thread scheduler and the CLR see fit.
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
Although active threads can be moved between application boundaries, a given thread can only execute
Chapter 3 - C# Language Fundamentals
within a single application domain at any point in time (in other words, it is impossible for a single thread to
Chapter 4 - Object-Oriented Programming with C#
be doing work in more than one AppDomain). If you wish to gain access to the AppDomain that is currently
Chapter 5 - Exceptions and Object Lifetime
hosting the Thread type, call the static Thread.GetDomain method:
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
// Thread.GetDomain() returns an AppDomain type.
Chapter 8 - Advanced C# Type Construction Techniques
Console.WriteLine(Thread.GetDomain().FriendlyName);
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
ChapterA single10thread- Processes,may alsoAppDobe movedains, Contexts,into a particularand Threadscontext at any given time, and may be relocated within
Chaptera new context11 - Typeat theR flectwhimon,ofLatetheBinding,CLR. If youand wishAttributeto programmatically-Based Programmingdiscover the current context a
PartthreadFourhappens- Leveragingto betheexecuting.NET Librariesin, make use of the static Thread.CurrentContext property:
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
// CurrentContext returns a Context type.
ChapterConsole14.-WriteLine(ThreadA Better Painting Fr mewo.CurrentContextk (GDI+) .ContextID);
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
As you would guess, the CLR is the entity that is in charge of moving threads into (and out of) application
Chapter 17 - Data Access with ADO.NET
domains and contexts. As a .NET developer, you are able to remain blissfully unaware where a given
Part Five - Web Applications and XML Web Services
thread ends up (or exactly when it is placed into its new boundary). Nevertheless, you should be aware of
Chapter 18 - ASP.NET Web Pages and Web Controls
the underlying model.
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
The Problem of Concurrency and Thread Synchronization
Index
List of Figures
One of the many joys (read: painful aspects) of multithreaded programming is that you have little control
List of Tables
over how the underlying operating system makes use of its threads. For example, if you craft a block of code that creates a new thread of execution, you cannot guarantee that the thread executes immediately. Rather, such code only instructs the OS to execute the thread as soon as possible (which is typically when the thread scheduler gets around to it).
Furthermore, given that threads can be moved between application and contextual boundaries as required by the CLR, you must be mindful of which aspects of your application are thread-volatile and which operations are atomic. (Thread-volatile operations are the dangerous ones!) For example, assume a given thread is accessing a shared point of data (or type member), and begins to modify its contents. Now assume that this thread is instructed to suspend its activity (by the thread scheduler) to allow another thread to access the same point of data.
If the original thread was not completely finished with its current modification of the type, the second incoming thread may be viewing a partially modified object. At this point, the second thread is basically reading bogus values, which is sure to give way to extremely odd (and very hard to find) bugs (which are even harder to replicate and thus debug).
Atomic operations, on the other hand, are always safe in a multithreaded environment, and yet there are
C# and the .NET Platform, Second Edition
very few operations in .NET that are guaranteed to be atomic. Even a simple assignment statement to a
by Andrew Troelsen ISBN:1590590554
double is not atomic! Unless the .NET Framework documentation specifically says an operation is atomic,
Apress © 2003 (1200 pages)
you must assume it is thread-volatile and take precautions.
This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
Given this, it should be clear that multithreaded application domains are in themselves quite volatile, as
architectural issues for .NET developers.
numerous threads can operate on the shared functionality at (more or less) the same time. To protect an application's resources from possible corruption, the .NET developer must make use of any number of
threading primitives such as locks, monitors, and the [synchronization] attribute, to control access among
Table of Contents
the executing threads.
C# and the .NET Platform, Second Edition
Introduction
Although the .NET platform cannot make the difficulties of building robust multi-threaded applications PartcompletelyOne - Introducingdisappear,C#theandprocessthe .NEThasPlatformbeen simplified considerably. Using types defined within the ChapSystemr 1.Threading- The Philosophynamespace,of .NETyou are able to spawn additional threads with minimal fuss and bother.
ChapterLikewise,2 when- Buildingit is timeC# Applicationsto lock down shared points of data, you will find additional types that provide the
PartsameTwofunctionality- The C# Programmingas the raw Win32Languagethreading primitives (using a much cleaner object model).
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
MultithreadedC# andProgrammingthe .NET Platform,viaSecondDelegatesEdition
by Andrew Troelsen |
ISBN:1590590554 |
Before checking out the details of programming with threads under the .NET platform, it is worth
Apress © 2003 (1200 pages)
reiterating that the whole point of creating additional threads is to increase the overall functionality of a
This comprehensive text starts with a brief overview of the
given applicationC#to thelanguageuser. Recall,and thenhowever,quickly movesthat manyto keycommontechnicalprogrammingand tasks that traditionally required manual archicreationecturalof threadsissues for(e.g.NET., remotedevelopersmethod. invocations, manipulating IO streams, and so forth) are automated using asynchronous delegates (first examined in Chapter 7).
TableAs youf Contentshave seen throughout various points in this text (and will see in future chapters), when you invoke a C#delegateand theasynchronously,.NET Platform, Secondthe CLREditionautomatically creates a worker thread to handle the task at hand.
However, if you have an application-specific task to account for (such as printing a lengthy document or
Introduction
working with a GUI display), you will be required to manually manipulate threads if you wish to keep your
Part One - Introducing C# and the .NET Platform
primary thread responsive. This disclaimer aside, allow me to formally introduce the System.Threading
Chapter 1 - The Philosophy of .NET
namespace.
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
The SystemC#.Threadingand the .NET Platform,NamespaceSecond Edition
by Andrew Troelsen |
ISBN:1590590554 |
Under the .NET platform, the System.Threading namespace provides a number of types that enable
Apress © 2003 (1200 pages)
multithreaded programming. In addition to providing types that represent a specific CLR thread, this
This comprehensive text starts with a brief overview of the
namespace alsoC#defineslanguagetypesandthatthencanquicklymanagemovesa collectionto key technicalof threadsand(ThreadPool), a simple (non-GUI based) Timer class,architecturaland variousis uestypesforused.NET todevelopersprovide .synchronized access to shared resources. Table 10-6 lists some (but not all) of the core members of this namespace.
Table of Contents |
|
|
|
|
|
|
|||
|
Table 10-6: Select Types of the System.Threading Namespace |
||||||||
C# and the .NET Platform, Second Edition |
|
|
|||||||
|
|||||||||
IntroductionSystem.Threading |
|
|
|
Meaning in Life |
|
|
|||
PartTypeOne - Introducing C# and the .NET Platform |
|
|
|||||||
|
|
|
|
|
|
|
|
||
|
|
Chapter 1 - The Philosophy of |
|
|
|
.NET |
|
|
|
|
|
Interlocked |
|
|
|
Provides atomic operations for objects that are shared by multiple |
|
|
|
|
Chapter 2 |
- Building C# Applications |
|
|
|||||
|
|
|
|
|
|
|
threads. |
|
|
Part Two - The C# Programming |
|
|
|
Language |
|
|
|||
|
|
|
|||||||
ChapterMonitor3 |
- C# Language FundamentalsProvides the synchronization of threading objects using locks and |
|
|
||||||
|
|
Chapter 4 - Object-Oriented |
|
|
wait/signals. |
|
|
||
|
|
Programming with C# |
|
|
|||||
|
|
|
|
|
|
||||
|
|
Chapter 5 - Exceptions and Object Lifetime |
|
|
|||||
|
|
Mutex |
|
|
|
|
Synchronization primitive that can be used for interprocess |
|
|
|
Chapter 6 |
- Interfaces and Collections |
|
|
|||||
|
|
|
|
|
|
|
synchronization. |
|
|
|
|
|
|
|
|
|
|
||
|
|
Chapter 7 - Callback Interfaces, |
|
|
Delegates, and Events |
|
|||
|
|
Thread |
- Advanced C# Type |
|
|
|
Represents a thread that executes within the CLR. Using this type, |
|
|
|
Chapter 8 |
|
|
|
Construction Techniques |
|
|
||
Part Three - Programming with |
|
|
|
you are able to spawn additional threads in the originating |
|
|
|||
|
|
|
.NET Assemblies |
|
|
||||
|
|
|
|
|
|
|
AppDomain. |
|
|
|
Chapter 9 - Understanding .NET Assemblies |
|
|
ChapterThreadPool10 - Processes, AppDomainThis,typeContexts,managesand Threadsrelated threads in a given process.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Timer |
Provides a mechanism for executing a method at specified intervals. |
Part Four - Leveraging the .NET Libraries
ChapterThreadStart12 - Object SerializationDelegateand the .NETthatRemotingspecifiesLayerthe method to call for a given Thread.
Chapter 13 - Building a Better Window (Introducing Windows Forms)
ThreadState |
This enum specifies the valid states a thread may take (Running, |
Chapter 14 - A Better Painting Framework (GDI+)
Aborted, etc.).
Chapter 15 - Programming with Windows Forms Controls
ChapterTimerCallback16 - The System.IO NamespaceDelegate type used in conjunction with Timer types.
Chapter 17 - Data Access with |
ADO.NET |
ThreadPriority |
This enum specifies the valid levels of thread priority. |
Part Five - Web Applications and |
XML Web Services |
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Examining the Thread Class
Chapter 20 - XML Web Services
Index
The most primitive of all types in the System.Threading namespace is Thread. This class represents an
List of Figures
object-oriented wrapper around a given path of execution within a particular AppDomain. This type also
List of Tables
defines a number of methods (both static and shared) that allow you to create new threads from the scope of the current thread, as well as suspend, stop, and destroy a particular thread. Consider the list of core static members given in Table 10-7.
Table 10-7: Key Static Members of the Thread Type
|
|
|
|
|
|
|
|
|
|
Thread StaticC# and theMeaning.NET Platform,in LifeSecond Edition |
|
|
|||
|
|
Member |
by Andrew Troelsen |
ISBN:1590590554 |
|
||
|
|
|
|
|
|
|
|
|
|
CurrentContext |
Apress © 2003 (1200 pages) |
|
|
||
|
|
|
|
This (read-only) property returns the context the thread is currently |
|
||
|
|
|
This comprehensive text starts with a brief overview of the |
|
|||
|
|
|
|
|
running. |
|
|
|
|
|
C# language |
and then quickly moves to key technical and |
|
||
|
|
CurrentThread |
architectural |
|
issues for .NET developers. |
|
|
|
|
|
|
This (read-only) property returns a reference to the currently running |
|
||
|
|
|
|
|
thread. |
|
|
|
|
|
|
|
|
||
|
|
GetDomain() |
|
|
Returns a reference to the current AppDomain (or the ID of this |
|
|
Table of Contents |
|
|
|
|
|
||
C# and the .NET Platform, Seconddomain)Editionin which the current thread is running. |
|
||||||
|
|
GetDomainID() |
|
|
|
|
|
|
Introduction |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
PartSleep()One - Introducing C# andSuspendsthe .NET Platformthe current thread for a specified time. |
|
||||||
|
|
|
|
|
|
|
|
Chapter 1 - The Philosophy of .NET
Thread also supports the object level members shown in Table 10-8.
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
|
Table 10-8: Select Instance Level Members of the Thread Type |
|||||||
|
Chapter 3 |
- C# Language Fundamentals |
||||||
|
|
|
|
|
|
|
|
|
|
|
Chapter 4 |
- Object-Oriented Programming with C# |
|
|
|||
|
|
Thread Instance |
|
|
Meaning in Life |
|
|
|
|
Chapter 5 |
- Exceptions and Object Lifetime |
|
|
||||
|
|
Level Member |
|
|
|
|
|
|
|
|
Chapter 6 |
- Interfaces and Collections |
|
|
|||
|
|
|
||||||
|
|
Abort() |
- Callback Interfaces, |
|
|
This method instructs the CLR to terminate the thread ASAP. |
|
|
|
Chapter 7 |
|
Delegates, and Events |
|
|
|||
|
|
|||||||
|
|
Chapter 8 |
- Advanced C# Type |
|
|
Construction Techniques |
|
|
|
|
IsAlive |
|
|
|
This property returns a Boolean that indicates if this thread has |
|
|
Part Three - Programming with .NET Assemblies |
|
|
||||||
|
|
|
|
|
|
been started. |
|
|
|
|
|
|
|
|
|
|
|
|
|
Chapter 9 |
- Understanding .NET |
|
Assemblies |
|
||
|
|
IsBackground |
|
|
Gets or sets a value indicating whether or not this thread is a |
|
|
|
|
Chapter 10 |
- Processes, AppDomains, |
|
Contexts, and Threads |
|
|
||
|
|
|
|
|
|
background thread. |
|
|
|
Chapter 11 |
- Type Reflection, Late |
|
|
Binding, and Attribute-Based Programming |
|
|
|
|
|
|
||||||
Part Four - Leveraging the .NET |
Libraries |
|
|
|||||
|
|
Name |
|
|
|
This property allows you to establish a friendly textual name of the |
|
|
Chapter 12 |
- Object Serialization |
and the .NET Remoting Layer |
|
|
||||
|
|
|
|
|
|
thread. |
|
|
|
|
|
|
|
|
|||
|
|
Chapter 13 |
- Building a Better Window (Introducing Windows Forms) |
|
|
|||
|
|
Priority |
|
|
|
Gets or Sets the priority of a thread, which may be assigned a |
|
|
|
Chapter 14 |
- A Better Painting Framework (GDI+) |
|
|
||||
|
|
|
|
|
|
value from the ThreadPriority enumeration. |
|
|
|
|
Chapter 15 |
- Programming with |
Windows Forms Controls |
|
|
||
|
|
|
|
|||||
|
ChapterThreadState16 - The System.IO NamespaceGets the state of this thread, which may be assigned a value from |
|
|
|||||
|
Chapter 17 |
- Data Access with ADO.theNETThreadState enumeration. |
|
|
||||
|
|
|
|
|
|
|||
Part Five - Web Applications and |
XML Web Services |
|
|
|||||
|
|
Interrupt() |
|
|
Interrupts the current thread. |
|
|
|
|
Chapter 18 |
- ASP.NET Web Pages |
|
and Web Controls |
|
|
||
|
|
|
|
|
|
|||
|
ChapterJoin()19 |
- ASP.NET Web ApplicationsInstructs a thread to wait for another thread to complete. |
|
|
||||
|
|
|
|
|
|
|
|
|
Chapter 20 - XML Web Services
Resume()
Index
Start()
List of Figures
List of Tables
Suspend()
Resumes a thread that has been previously suspended. Instructs the CLR to execute the thread ASAP.
Suspends the thread. If the thread is already suspended, a call to Suspend() has no effect.
Gathering Basic Thread Statistics
Recall that the entry point of an executable assembly (i.e., the Main() method) runs on the primary thread of execution. To illustrate the basic use of the Thread type, assume you have a new console application named ThreadStats. The static Thread.CurrentThread property retrieves a Thread type that represents the currently executing thread. Thus, if you trigger this member within the scope of Main(), you are able to print out various statistics about the primary thread:
using System.Threading;
...
static void Main(string[] args)
{ |
C# and the .NET Platform, Second Edition |
|
|
// Get some info about the current thread. |
|
|
by Andrew Troelsen |
ISBN:1590590554 |
|
Thread primaryThread = Thread.CurrentThread; |
|
|
Apress © 2003 (1200 pages) |
|
|
// Get name of current AppDomain and context ID. |
|
|
This comprehensive text starts with a brief overview of the |
|
|
Console.WriteLine("***** Primary Thread stats *****"); |
|
|
C# language and then quickly moves to key technical and |
|
|
Console.WriteLine("Name of current AppDomain: {0}", |
|
|
architectural issues for .NET developers. |
|
|
Thread.GetDomain().FriendlyName); |
|
|
Console.WriteLine("ID of current Context: {0}", |
|
Table of ContentsThread.CurrentContext.ContextID); |
||
C# and theConsole.WriteLine("Thread.NET Platform, Second Edition |
Name: {0}", primaryThread.Name); |
Console.WriteLine("Apt state: {0}", primaryThread.ApartmentState);
Introduction
Console.WriteLine("Alive: {0}", primaryThread.IsAlive);
Part One - Introducing C# and the .NET Platform
Console.WriteLine("Priority Level: {0}", primaryThread.Priority);
Chapter 1 - The Philosophy of .NET
Console.WriteLine("Thread State: {0}", primaryThread.ThreadState);
Chapter 2 - Building C# Applications
Console.WriteLine();
Part Two - The C# Programming Language
}
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Naming Threads
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
When you run this application, notice how the name of the default thread is currently an empty string.
Chapter 8 - Advanced C# Type Construction Techniques
Under .NET, it is possible to assign a human-readable string to a thread using the Name property. Thus, if
Part Three - Programming with .NET Assemblies
you wish to be able to programmatically identify the primary thread via the moniker "ThePrimaryThread,"
Chapter 9 - Understanding .NET Assemblies you could write the following:
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Name the thread.
Part Four - Leveraging the .NET Libraries
primaryThread.Name = "ThePrimaryThread";
Chapter 12 - Object Serialization and the .NET Remoting Layer
Console.WriteLine("This thread is called: {0}", primaryThread.Name);
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
.NET Threads and Legacy COM Apartments
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Also notice that every Thread type has a property named ApartmentState. Those of you who come from a
Part Five - Web Applications and XML Web Services
background in classic COM may already be aware of apartment boundaries. In a nutshell, COM
Chapter 18 - ASP.NET Web Pages and Web Controls
apartments were a unit of isolation used to group COM objects with similar threading needs. Under the
Chapter 19 - ASP.NET Web Applications
.NET platform however, apartments are no longer used by managed objects. If you happen to be making Chapteruse of COM20 - XMLobjectsWebfromServicesmanaged code (via the interoperability layer), you are able to establish the
Indexapartment settings that should be simulated to handle the coclass in question. To do so, the .NET base
Listclassof Flibrariesgures provide two attributes to mimic the single-threaded apartment (STAThreadAttribute, which is Listaddedof Tablesby default to your application's Main() method when using the VS .NET IDE) and multithreadedapartment (MTAThreadAttribute) of classic COM. In fact, when you create a new *.exe .NET application type, the primary thread is automatically established to function as an STA:
//This attribute controls how the primary thread should
//handle COM types.
[STAThread]
static void Main(string[] args)
{
// COM objects will be placed into an STA.
}
If you wish to specify support for the MTA, simply adjust the attribute:
[MTAThread] |
C# and the .NET Platform, Second Edition |
|
static void Main(string[] args) |
ISBN:1590590554 |
|
{ |
by Andrew Troelsen |
|
Apress © 2003 (1200 pages) |
|
// COM objects will be placed into the MTA.
} |
This comprehensive text starts with a brief overview of the |
|
C# language and then quickly moves to key technical and |
||
|
||
|
architectural issues for .NET developers. |
Of course, if you don't know (or care) about classic COM objects, you can simply leave the [STAThread]
attribute on your Main() method. Doing so will keep any COM types thread-safe without further work on
Table of Contents
your part. If you don't make use of COM types within the Main() method, the [STAThread] attribute does
C# and the .NET Platform, Second Edition nothing.
Introduction
Part One - Introducing C# and the .NET Platform
Setting a Thread's Priority Level
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
As mentioned, we programmers have little control over when the thread scheduler switches between
Part Two - The C# Programming Language
threads. We can, however, mark a given thread with a priority level to offer a hint to the CLR regarding the
Chapter 3 - C# Language Fundamentals
importance of the thread's activity. By default, all threads have a priority level of normal. However this can
Chapter 4 - Object-Oriented Programming with C#
be changed at any point in the thread's lifetime using the ThreadPriority property and the related
Chapter 5 - Exceptions and Object Lifetime
ThreadPriority enumeration:
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
public enum System.Threading.ThreadPriority
Chapter 8 - Advanced C# Type Construction Techniques
{
Part Three - Programming with .NET Assemblies
AboveNormal, BelowNormal,
Chapter 9 - Understanding .NET Assemblies
Highest, Lowest,
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Normal, // Default value.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
}
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Always keep in mind that a thread with the value of ThreadPriority.Highest is not necessarily guaranteed to
Chapter 13 - Building a Better Window (Introducing Windows Forms)
given the highest precedence. Again, if the thread scheduler is preoccupied with a given task (e.g.,
Chapter 14 - A Better Painting Framework (GDI+)
synchronizing an object, switching threads, moving threads, or whatnot) the priority level will most likely be
Chapter 15 - Programming with Windows Forms Controls
altered accordingly. However, all things being equal, the CLR will read these values and instruct the
Chapter 16 - The System.IO Namespace
thread scheduler how to best allocate time slices. All things still being equal, threads with an identical
Chapter 17 - Data Access with ADO.NET
thread priority should each receive the same amount of time to perform their work.
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Note Again, you will seldom (if ever) need to directly alter a thread's priority level. In theory, it is
Chapter 19 - ASP.NET Web Applications
possible to jack up the priority level on a set of threads, thereby preventing lower priority threads Chapter 20 from- XMLexecutingWeb Servicesat their required levels (so use caution).
Index
List of Figures
List of Tables