Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
194
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 9: Memory and Resource Management

1

 

 

 

Overview

Topic Objective

To provide an overview of the module topics and objectives.

Lead-in

Objects in the Microsoft

.NET Framework use memory resources and may use other resources, such as file handles. For software to run properly, these resources must be well managed.

!Memory Management Basics

!Non-Memory Resource Management

!Implicit Resource Management

!Explicit Resource Management

!Optimizing Garbage Collection

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Objects in the Microsoft® .NET Framework use memory resources and may use other resources, such as file handles. For software to run properly, these resources must be well managed. In other words, they must be properly allocated and released.

After completing this module, you will be able to:

!

!

Describe how garbage collection manages object memory.

Implicitly manage non-memory resources by using a destructor’s finalize code.

!Explicitly manage non-memory resources by using client-controlled deterministic release of resources.

!

!

!

Write code by using the temporary resource usage design pattern. Programmatically control the behavior of the garbage collection. Describe advanced garbage collection features.

2Module 9: Memory and Resource Management

" Memory Management Basics

Topic Objective

To provide an overview of the section topics.

Lead-in

A major feature of the .NET Framework common language runtime is that the runtime automatically handles the allocation and release of an object’s memory resources.

!Developer Backgrounds

!Manual vs. Automatic Memory Management

!Memory Management of .NET Framework Types

!Simple Garbage Collection

*****************************ILLEGAL FOR NON-TRAINER USE******************************

A major feature of the .NET Framework common language runtime is that the runtime automatically handles the allocation and release of an object’s memory resources. In most cases, automatic memory management enhances code quality and developer productivity without negatively impacting expressiveness or performance.

Understanding how the .NET Framework facilitates resource management is essential for writing correct and efficient code.

In this section, you will learn about memory management in the .NET

Framework, including simple garbage collection.

Module 9: Memory and Resource Management

3

 

 

 

Developer Backgrounds

Topic Objective

To discuss various developer backgrounds with regard to memory management.

Lead-in

Your experience with memory management will vary depending upon your development background.

!COM

#Manually implement reference counting and handle circular references

!C++

#Manually use the new operator and delete operator

!Visual Basic

#Accustomed to automatic memory management

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Your experience with memory management will vary depending upon your development background. In certain situations, you will need to adapt your programming practices to the automatic memory management that is provided by the common language runtime.

COM Developers

COM developers are accustomed to implementing reference counting as a manual memory management technique. Each time an object is referenced, a counter is incremented. When a reference to an object goes out of scope, the counter is decremented. When an object’s reference count reaches zero, the object is terminated and its memory is freed.

The reference counting scheme is the source of many bugs. If the reference counting rules are not followed precisely, objects may be freed prematurely or unreferenced objects may accumulate in memory.

Circular references are also a common source of bugs. A circular reference occurs when a child object has a reference to a parent object, and the parent object has a reference to the child object. Circular references prevent either object from being released or destroyed. The only solution is for the parent and child objects to agree on a fixed pattern of usage and destruction, such as where the parent always deletes the child first.

When you develop applications in a managed language, the runtime’s garbage collector eliminates the need for reference counting and, as a result, the bugs that can arise from this manual memory management scheme.

4Module 9: Memory and Resource Management

C++ Developers

C++ developers are accustomed to the tasks that are related to manual memory management. In C++, when you allocate memory for an object by using the new operator, you must release the object’s memory by using the delete operator. This can lead to errors such as forgetting to release an object and causing a memory leak, or attempting to access memory for an object that has already been released.

When you develop applications by using the Managed Extensions for C++, or another managed language, you do not have to use the delete operator to release an object. The garbage collector does this for you automatically when the object is no longer being used by the application.

C++ developers may be accustomed to avoiding the use of short-term objects because of the associated cost of manually managing the memory for these objects. For managed short-term objects that are created and then go out of scope between collections, the cost of allocating and releasing memory is extremely low.

In the .NET Framework, the garbage collector is actually optimized to manage objects with short lifetimes. When you develop managed applications, it is appropriate to use short-term objects in situations where they simplify your code.

Visual Basic Developers

Microsoft Visual Basic® developers are accustomed to automatic memory management. If you are a Visual Basic developer, the programming practices with which you are familiar apply to the majority of the managed objects that you create in the .NET Framework. However, you should take special note of the suggested design pattern for a Dispose method to use when you create or use objects that encapsulate unmanaged resources.

Module 9: Memory and Resource Management

5

 

 

 

Manual vs. Automatic Memory Management

Topic Objective

To introduce the advantages of automatic memory management in the .NET Framework.

Lead-in

Manual memory management requires that you manage the allocation and deallocation of blocks of memory.

!Manual Memory Management

#Programmer manages memory

!Common Problems

#Failure to release memory

#Invalid references to freed memory

!.NET Runtime Provides Automatic Memory Management

#Eases programming task

#Eliminates a potential source of bugs

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Manual memory management requires that you manage the allocation and deallocation of blocks of memory. The NET Framework common language runtime provides automatic memory management so that you are freed from this time-consuming and difficult task.

Manual Memory Management

The following table provides examples of manual memory management in different programming languages, C and C++, and in COM.

Language or

 

environment

Example of manual memory management

Cmalloc and free functions

C++

new and delete operators

COM

AddRef and Release reference counting methods

Automatic Memory Management in the .NET Framework

The .NET Framework common language runtime automatically handles managed object memory and manages references to these objects, releasing managed objects when they are no longer being used. This automatic memory management eliminates the possibility of programming errors that can cause memory leaks and the use of memory that has already been freed. With automatic memory management, you no longer have to deal with complex bugs that are associated with reference counting, circular reference leaks, or dangling references.

6Module 9: Memory and Resource Management

Memory Management of .NET Framework Types

Topic Objective

To explain how a value’s type affects how the value is managed in memory.

Lead-in

In .the NET Framework, all values have a type, which may be a value type or a reference type.

!Instances of Value Types Use Stack Memory

#Allocation and deallocation are automatic and safe

!Managed Objects Are Reference Types and Use Heap Memory

#Created by calls to the new operator

#Freed by garbage collection

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In the .NET Framework, all values have a type, which may be a value type or a reference type. Each value’s type affects how that value is managed in memory.

Instances of Value Types

Instances of value types are stored in memory that is allocated on the stack.

Allocation and deallocation of memory occur automatically as follows:

!Allocation

Memory for an instance of a value type is created when the activation record for its scope is pushed on to the stack.

!Deallocation

Memory is deallocated when the scope’s activation record, which contains the value type instance, is popped from the stack.

Value types are always accessed directly. You cannot create a reference to a value type, and therefore you cannot refer to a value instance that has been deallocated. As a result, there is no danger of creating a dangling reference to a value type.

Module 9: Memory and Resource Management

7

 

 

 

Instances of Reference Types

Managed objects are reference types, which you create by calls to the new operator. The memory of these objects is allocated in the common language runtime managed heap. You can access reference types only through a reference to that storage. The use of references enables garbage collection to track outstanding references to a particular instance and to free that object’s heap memory when appropriate.

A managed object’s heap memory is only released through garbage collection when there are no reachable references to that object. This mechanism ensures that there will be no invalid references to the object’s freed memory and thus no dangling references.

8Module 9: Memory and Resource Management

Simple Garbage Collection

Topic Objective

To explain how simple garbage collection works in the .NET Framework.

Lead-in

Garbage collection is triggered when an application creates an object, and there is not enough space left in the heap to provide memory for the object.

!Simple Garbage Collection Algorithm

#Wait until managed code threads are in a safe state

#Build a graph of all reachable objects

#Move reachable objects to compact heap

-Unreachable objects’ memory is reclaimed

#Update references to all moved objects

!Reference Cycles Are Handled Automatically

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Typically, garbage collection is triggered when an application creates an object, and there is not enough space left in the heap to provide memory for the object. Alternatively, you can invoke garbage collection programmatically. This process is discussed in Optimizing Garbage Collection in this module.

The Garbage Collection Algorithm

Whether garbage collection occurs automatically or you invoke it programmatically, the garbage collection algorithm is used to find any objects in the heap whose memory can be reclaimed. Such objects include objects that are no longer being used by the application. If garbage collection can reclaim enough objects to free sufficient memory, memory for the new objects can be allocated. Otherwise, an OutOfMemoryException is thrown.

For the sake of simplicity, this topic describes the simple garbage collection process. The finalization phase and optimization details are discussed in Implicit Resource Management in this module.

Simple Garbage Collection Process

Simple garbage collection uses the following process:

1.Waits until other managed threads reach a safe state, for example, suspended.

The garbage collection process modifies managed objects and their references. Therefore it must first wait until other managed threads are suspended.

2.Builds a graph of all reachable objects.

3.Compacts the heap by moving reachable objects.

By moving reachable objects down in the heap, garbage collection reclaims the space in the heap that was used by unreachable objects.

4.Updates all application references to moved objects.

Module 9: Memory and Resource Management

9

 

 

 

Building the Graph of Reachable Objects

Garbage collection accesses the collection of root references that are maintained by the runtime. Each application has a logical collection of root references. The collection contains all of the managed object references from global and static objects and local variables that are currently on the stack and in CPU registers.

To build the graph of reachable objects, garbage collection performs the following actions.

1.It adds all of the objects that are referenced by each root reference.

2.It recursively adds objects that are referenced by any added object.

Before an object is added to the graph, garbage collection checks to ensure that the object is not already in the graph. This check prevents garbage collection from entering an infinite loop that is caused by circular references.

At the end of the process, any object that is not in the reachable object graph is considered unreachable and therefore garbage.

Reference Cycles Handled Automatically

An object is reachable only if there is a path from a root reference to that object. Therefore, reference cycles between unreachable objects will not prevent the objects’ memory from being released by the garbage collection process. For example, if A references B and B references A, then both objects will be garbage collected when they are no longer reachable from a root reference.

10 Module 9: Memory and Resource Management

Multimedia: Simple Garbage Collection

Topic Objective

To illustrate the .NET Framework garbage collection process.

Lead-in

This animation illustrates the

.NET Framework common language runtime’s garbage collection process.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

To launch the animation, click the button in the lower left corner of the slide. To play the animation, click the Simplified Garbage Collection button at the top of the screen, and then click the play button in the lower left corner of the screen.

This animation illustrates the .NET Framework common language runtime garbage collection process.

Note Compiler optimization is disabled in this scenario to prevent an object from becoming eligible for garbage collection earlier than would be expected. Otherwise, the compiler could optimize away assignments to local variables that are never observed by a later read. This optimization could result in an object being subject to garbage collection before its reference is assigned to null.

!The common language runtime allocates memory resources for reference type objects in the section of the application’s memory that is called the managed heap.

!When there is insufficient space in the managed heap, the common language runtime executes the garbage collection algorithm to remove objects that are no longer being used by the application.

Соседние файлы в папке c#