Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# and the NET Platform, Second Edition - Andrew Troelsen.pdf
Скачиваний:
67
Добавлен:
24.05.2014
Размер:
22.43 Mб
Скачать
Part Two - The C# Programming Language
Chapter 2 - Building C# Applications
Chapter 1 - The Philosophy of .NET
Part One - Introducing C# and the .NET Platform

Garbage Collection Optimizations

 

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

Now that you have seen two approaches that may be used to ensure the proper cleanup of your custom

Apr ss © 2003 (1200 pages)

types, let's dig a bit deeper into the functionality of the .NET garbage collector and check out the topic of

This comprehensive text starts with a brief overview of the objectgenerationsC#. language and then quickly moves to key technical and

architectural issues for .NET developers.

When the CLR is attempting to locate unreachable objects, is does not literally walk over each and every object placed on the managed heap looking for orphaned roots. Doing so would involve considerable

Tabletime,ofespeciallyContentsin larger (i.e., real-world) applications.

C# and the .NET Platform, Second Edition

To help optimize the collection process, each object on the heap is assigned to a given "generation." The

Introduction

idea behind generations is simple: The longer an object has existed on the heap, the more likely it is to stay there (for example, the object implementing an application's Main() method). Conversely, objects that have been recently placed on the heap are more likely to be dereferenced by the application rather quickly (such as an object created within a method scope). Given these assumptions, each object belongs to one

of the following generations (as of .NET version 1.1):

Chapter 3 - C# Language Fundamentals

ChapterGeneration4 - Object0:-IdentifiesOriented Programmingnewly allocatedwith C#object that has never been marked for collection.

Chapter 5 - Exceptions and Object Lifetime

Generation 1: Identifies an object that has survived a garbage collection sweep (i.e., it was marked for

Chapter 6 - Interfaces and Collections

collection, but was not removed due to the fact that the heap had enough free space).

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Generation 2: Identifies an object that has survived more than one sweep of the garbage collector.

Part Three - Programming with .NET Assemblies

ChapterNow, when9 - Understandingcollection occurs,.NET Assembliesthe GC marks and sweeps all generation 0 objects first. If this results in the

Chapterrequired10amount- Processes,of memory,AppDomains,the remainingContexts,objectsand Threadsare promoted to the next available generation. If all Chaptergeneration11 -0TypeobjectsReflection,have beenLate removedBinding, andfromAttheributeheap,-BasedbutProgramore memoryming is still necessary, generation 1 PartobjectsFourare- Leveragingmarked andtheswept,.NET Librariesfollowed (if necessary) by generation 2 objects. In this way, the newer

objects (i.e., local variables) are removed quickly while an older object (i.e., the object defining the Main()

Chapter 12 - Object Serialization and the .NET Remoting Layer

method) is assumed to be in use. In a nutshell, the GC is able to quickly free heap space using the

Chapter 13 - Building a Better Window (Introducing Windows Forms)

generation as a baseline.

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#.GCand Typethe .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Like everything in the .NET universe, you are able to interact with the garbage collector using a base class

Apress © 2003 (1200 pages)

library type, which in this case is System.GC. This type allows you to interact with the garbage collector

This comprehensive text starts with a brief overview of the

using a small setC#of staticlanguagemembersand then. Tablequickly5-2movgives atorundownkey technicalof someand of the more interesting items.

architectural issues for .NET developers.

Table 5-2: Select Members of the System.GC Type

 

 

 

 

 

 

TableSystem.GCof ContentsMember

 

Meaning in Life

 

 

 

 

 

 

C# and the .NET Platform, Second Edition

 

 

Collect()

 

 

Forces the GC to call the Finalize() method for every object on the

 

Introduction

 

managed heap. You can also (if you choose) specify the generation to

 

 

 

 

 

 

Part One - Introducing C# and the .NET Platform

 

 

 

 

 

sweep .

 

 

Chapter 1 - The Philosophy of

.NET

 

 

 

 

ChapterGetGeneration()2 - Building C# ApplicationsReturns the generation to which an object currently belongs.

 

 

 

 

 

 

Part Two - The C# Programming

 

Language

 

 

MaxGeneration

 

This property returns the maximum of generations supported on the

 

Chapter 3

- C# Language

 

Fundamentals

 

 

 

 

 

target system.

 

 

Chapter 4 - Object-Oriented

 

Programming with C#

 

 

 

 

 

ChapterReRegisterForFinalize()5 - Exceptions and

 

ObjectSetsLifetimea flag indicating that a suppressed object should be reregistered

 

 

Chapter 6

- Interfaces and

 

as finalizable. This (of course) assumes the object was marked as

 

 

 

Collections

 

 

 

 

 

nonfinalizable using SuppressFinalize().

 

 

Chapter 7 - Callback Interfaces,

Delegates, and Events

 

 

 

 

 

 

 

 

 

Chapter 8

- Advanced C# Type Construction Tech iques

 

 

SuppressFinalize()

 

Sets a flag indicating that a given object should not have its Finalize()

 

Part Three - Programming withmethod.NET Assembliescalled.

 

Chapter 9

- Understanding .NET Assemblies

 

GetTotalMemory()

Returns the estimated amount of memory (in bytes) currently being

 

Chapter 10

- Processes, AppDomains, Contexts, and Threads

 

Chapter 11

 

used by all objects in the heap, including objects that are soon to be

 

- Type Reflection, Late Binding, and Attribute-Based Programming

 

 

 

destroyed. This method takes a Boolean parameter that is used to

Part Four - Leveraging the .NET Libraries

Chapter 12

 

specify if a garbage collection should occur during the method

- Object Serialization and the .NET Remoting Layer

 

 

 

invocation.

Chapter 13

- Building a Better

Window (Introducing Windows Forms)

Chapter 14

- A Better Painting Framework (GDI+)

Chapter 15

- Programming with Windows Forms Controls

Building Finalizable and Disposable Types

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

To illustrate programmatic interaction with the .NET garbage collector, let's retrofit the automobile's

Part Five - Web Applications and XML Web Services

destruction logic to support both an overridden Finalize() method as well as the IDisposable interface:

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

// Memory clean up.

Chapter 20 - XML Web Services

public class Car : IDisposable

Index

{

List of Figures

...

List of Tables

~Car()

{ // Clean up any internal unmanaged resouces. } public void Dispose()

{

//Clean up any internal resources.

...

//No need to finalize if user called Dispose(),

//so suppress finalization. GC.SuppressFinalize(this);

}

}

Notice that this iteration of the Car class supports both a C#-style destructor as well as the IDisposable interface. Here, your Dispose() method has been altered to call GC.SuppressFinalize(), which informs the system that it should no longer call the destructor for the specified object, as the end user has called

Dispose() manually (and has therefore cleaned up any internal resources of the Car type).

C# and the .NET Platform, Second Edition

To illustrate the interplayby AndrewbetweenTroelsenexplicit and implicit object deallocation,ISBN:1590590554assume the following updated Main() method. GivenApressthat© 2003two(1200of thepages)Car types have been manually disposed by the object user, these types do not haveThistheircomprehensivedestructor logictexttriggeredstarts withduea tobrieftheoverviewcall to GCof .theSuppressFinalize():

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

// Interacting with the GC.

public class GCApp

{

Table of Contents

public static int Main(string[] args)

C# and the .NET Platform, Second Edition

{

Introduction

// Add these cars to the managed heap.

Part One - Introducing C# and the .NET Platform

Car c1, c2, c3, c4;

Chapter 1 - The Philosophy of .NET

c1 = new Car("Car one", 40, 10);

Chapter 2 - Building C# Applications

c2 = new Car("Car two", 70, 5);

Part Two - The C# Programming Language

c3 = new Car("Car three", 200, 100);

Chapter 3 - C# Language Fundamentals

c4 = new Car("Car four", 140, 80);

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

// Manually dispose some objects.

Chapter 6 - Interfaces and Collections

c1.Dispose();

Chapter 7 - Callback Interfaces, Delegates, and Events

c3.Dispose();

Chapter 8 - AdvancedreturnC#0;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

The output can be seen in Figure 5-13.

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter

Windows Forms)

Chapter

 

Chapter

Controls

Chapter

 

Chapter

 

Part

Chapter

Chapter

Chapter 20 - XML Web Services

Figure 5-13: The interplay of finalization and disposal

Index

SOURCE

The FinalizedAndDisposedType project is included under the Chapter 5 subdirectory.

List of Figures

 

List ofCODETables

Forcing a Garbage Collection

Recall that the CLR will automatically trigger a garbage collection when the managed heap is full, which will happen "whenever." If you so choose, you are able to programmatically force the runtime to perform a garbage collection using the static GC.Collect() method. Now, understand that you should seldom (if ever) do so, given that the whole purpose of the managed heap is that it is maintained by forces outside of your control.

Nevertheless, assume you have an object-hungry application that is designed to run for a lengthy amount of time. To trigger a garbage collection, you could write the following:

//Force a garbage collection, and wait for

//each object to be finalized.

GC.Collect();

Part One - Introducing C# and the .NET Platform

GC.WaitForPendingFinalizers();

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

Note that you callApressGC.WaitForPendingFinalizers()© 2003 (1200 pages) after forcing a garbage collection cycle. In this way, you can rest assuredTthatis comprehensiveall finalizable objectstext startshavewithhada abriefchanceoverviewto performof the any necessary cleanup before continuing forwardC#. Dolanguagenote thatandthisthencallquicklywill suspendmoves tothekeycurrenttechnicalthreadand during the process (which is a

architectural issues for .NET developers.

good thing, as it ensures you don't invoke methods on a type that is currently being destroyed!).

Programmatically Interacting with Generations

Table of Contents

C# and the .NET Platform, Second Edition

To close this chapter, let's revisit the topic of an object's generation. Programmatically speaking, you are

Introduction

able to investigate the generation an object currently belongs to using GC.GetGeneration(). Furthermore,

GC.Collect() does allow you to specify which generation should be checked for valid application roots.

Chapter 1 - The Philosophy of .NET

Consider the following:

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

// Just how old are you?

Chapter 3 - C# Language Fundamentals

public static int Main(string[] args)

Chapter 4 - Object-Oriented Programming with C#

{

Chapter 5 - Exceptions and Object Lifetime

// Add these cars to the managed heap.

Chapter 6 - Interfaces and Collections

Car c1, c2, c3, c4;

Chapter 7 - Callback Interfaces, Delegates, and Events c1 = new Car("Car one", 40, 10);

Chapter 8 - Advanced C# Type Construction Techniques c2 = new Car("Car two", 70, 5);

Part Three - Programming with .NET Assemblies

c3 = new Car("Car three", 200, 100);

Chapter 9 - Understanding .NET Assemblies

c4 = new Car("Car four", 140, 80);

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

// Display generations.

Part FourConsole- Leveraging.WriteLine("C1the .NET Librariesis gen {0} ", GC.GetGeneration(c1));

Chapter Console12 - Obj ct.WriteLine("C2Serialization and theis.NETgenRemoting{0} ",LayerGC.GetGeneration(c2));

Chapter Console13 - Building.WriteLine("C3a B tter Window (Introducingis gen {0}Windows", GCForms).GetGeneration(c3));

Chapter Console14 - A B tter.WriteLine("C4Painting Frameworkis(GDI+)gen {0} ", GC.GetGeneration(c4));

Chapter 15 - Programming with Windows Forms Controls

// Dispose some cars manually.

Chapter 16 - The System.IO Namespace

c1.Dispose();

Chapter 17 - Data Access with ADO.NET

c3.Dispose();

Part Five - Web Applications and XML Web Services

// Collect all gen 0 objects?

Chapter 18 - ASP.NET Web Pages and Web Controls

GC.Collect(0);

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

// Display generations again (each will be promoted).

Index

Console.WriteLine("C1 is gen {0} ", GC.GetGeneration(c1));

List of Figures

Console.WriteLine("C2 is gen {0} ", GC.GetGeneration(c2));

List of Tables

Console.WriteLine("C3 is gen {0} ", GC.GetGeneration(c3)); Console.WriteLine("C4 is gen {0} ", GC.GetGeneration(c4)); return 0;

}

The output is shown in Figure 5-14.

Chapter 16 - The System.IO Namespace
Chapter 15 - Programming with Windows Forms Controls

 

Edition

 

ISBN:1590590554

 

a brief overview of the

 

to key technical and

 

.

Table

 

C# and

 

Part

 

Chapter

 

Chapter

 

Part

 

Chapter

 

Chapter

 

Chapter

 

Chapter

 

Chapter

 

Chapter

 

Part

 

Chapter

 

Chapter

Threads

Chapter

-Based Programming

Part

 

Chapter 12 - Object Serialization and the .NET Remoting Layer

Figure 5-14: Influencing an object's current generation

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Notice that when you request a collection of generation 0, each object is promoted to generation 1, given that these objects did not need to be removed from memory (as the heap was not exhausted). Also note

that if you request a collection of generation 2 objects, the objects that have survived the current garbage

Chapter 17 - Data Access with ADO.NET

collection remain at generation 2 (there is no generation greater than 2 as of .NET version 1.1).

Part Five - Web Applications and XML Web Services

ChapterAll things18 considered,- ASP.NET WebkeepPagesin minda thatWebyourControlsinteractions with the System.GC type should be slim to none.

ChapterThe whole19 -pointASP.NETof havingWeb Applicationsmanaged heap is to move the responsibility of memory management from

Chapteryour hands20 - intoXMLtheWebhandsServicesof the runtime.

Index

The Generations project is included under the Chapter 5 subdirectory.

SOURCE

List of Figures

 

CODE

 

List of Tables

 

Соседние файлы в предмете Программирование