net framework,memory management

20
Namespaces A namespace is a collection of different classes. All VB applications are developed using classes from the .NET System namespace. The namespace with all the built-in VB functionality is the System namespace. All other namespaces are based on this System namespace. Some Namespaces and their use: System: Includes essential classes and base classes for commonly used data types, events, exceptions and so on. System.Collections: Includes classes and interfaces that define various collection of objects such as list, queues, hash tables, arrays, etc. System.Data: Incl udes cl asses which lets us handle data fr om da ta sources System.Data.OleDb: Includes classes that support the OLEDB .NET pr ov ider System.Data.SqlClient : Includes classes that support the SQL Server .NET provider System.Diagnostics: Includes classes that allow to debug our application and to step through our code System.Drawing: Provides access to drawing methods System.Globalization: Includes classe s tha t spe cif y cul tur e-related informati on System.IO: Includes classes for data access with Files System.Net: Provides interface to protocols used on the internet System.Reflection: Includes clas ses and inter faces that return informat ion about types, methods and fields System.Security: Inc lud es cla sse s to sup por t the str ucture of common lan gua ge runtime security system System.Threading: Incl udes cl as ses an d interf aces to support multithr eaded applications System.Web: Incl ud es cl as ses an d interf aces th at su pp ort br owser-server communication System.Web.Services: Includes clas ses that let us build and use Web Services System.Windows.Forms: Includes classes for cr eati ng Wi ndows based forms System.XML: Includes classes for XML support Assemblies An assembly is the building block of a .NET application. It is a self des cri bing collection of code, resources, and metadata (data about data, example, name, size, version of a fi le is metadata about that fi le). An Assembly is a compli ed and versi oned collecti on of code and metad ata that forms an atomic func tiona l unit. Assemblies take the for m of a dynamic link library (.dll) file or executable program file (.exe) but they differ as they contain the information found in a type library and the information about everything else needed to use an application or component. All .NET programs are constructed from these Assemblies. Assemblies are made of two par ts: manifest, contains information about what is contained wi thin the asse mbly and modules, internal files of IL code which ar e ready to run. When progra mmi ng, we don't direct ly deal with assemblies as the CLR and the .NET framework takes care of that behind the scenes. The assembly file is visible in the Solution Explorer window of the project. An assembly includes:

Upload: dev-sharma

Post on 03-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 1/20

Namespaces

A namespace is a collection of  different classes. All VB applications are developedusing classes from the .NET System namespace. The namespace with all the built-in

VB functionality is the System namespace. All other namespaces are based on thisSystem namespace.

Some Namespaces and their use:

System: Includes essential classes and base classes for commonly used data types,events, exceptions and so on.

System.Collections: Includes classes and interfaces that define various collection of objects such as list, queues,

hash tables, arrays, etc.System.Data: Includes classes which lets us handle data from data sources

System.Data.OleDb: Includes classes that support the OLEDB .NET providerSystem.Data.SqlClient: Includes classes that support the SQL Server .NET provider

System.Diagnostics: Includes classes that allow to debug our application and to step

through our codeSystem.Drawing: Provides access to drawing methodsSystem.Globalization: Includes classes that specify culture-related information

System.IO: Includes classes for data access with Files

System.Net: Provides interface to protocols used on the internetSystem.Reflection: Includes classes and interfaces that return information about

types, methods and fieldsSystem.Security: Includes classes to support the structure of common language

runtime security system

System.Threading: Includes classes and interfaces to support multithreadedapplications

System.Web: Includes classes and interfaces that support browser-servercommunication

System.Web.Services: Includes classes that let us build and use Web ServicesSystem.Windows.Forms: Includes classes for creating Windows based forms

System.XML: Includes classes for XML support

Assemblies 

An assembly is the building block of a .NET application. It is a self describingcollection of code, resources, and metadata (data about data, example, name, size,

version of a file is metadata about that file). An Assembly is a complied andversioned collection of code and metadata that forms an atomic functional unit.

Assemblies take the form of a dynamic link library (.dll) file or executable program

file (.exe) but they differ as they contain the information found in a type library and

the information about everything else needed to use an application or component.All .NET programs are constructed from these Assemblies. Assemblies are made of two parts: manifest, contains information about what is contained within the

assembly and modules, internal files of  IL code which are ready to run. When

programming, we don't directly deal with assemblies as the CLR and the .NETframework takes care of that behind the scenes. The assembly file is visible in the

Solution Explorer window of the project.

An assembly includes:

Page 2: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 2/20

o Information for each public class or type used in the assembly – information

includes class or type names, the classes from which an individual class is

derived, etco Information on all public methods in each class, like, the method name and

return values (if any)o Information on every public parameter for each method like the parameter's

name and typeo Information on public enumerations including names and values

o Information on the assembly version (each assembly has a specific version

number)

o Intermediate language code to execute

o A list of types exposed by the assembly and list of other assemblies required

by the assembly

Image of a Assembly file is displayed below.

Page 3: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 3/20

The System.Net namespace provides a simple programming interface for many of the protocols used on

networks today. The WebRequest and WebResponse classes form the basis of what are called pluggable

protocols, an implementation of network services that enables you to develop applications that use

Internet resources without worrying about the specific details of the individual protocols.

An assembly is a collection of types and resources that forms a logical unit of functionality. All types in the

.NET Framework must exist in assemblies; the common language runtime does not support types outsideof assemblies. Each time you create a Microsoft Windows® Application, Windows Service, Class Library, orother application with Visual Basic .NET, you're building a single assembly. Each assembly is stored asan .exe or .dll file.

Note Although it's technically possible to create assemblies that span multiple files, you're not likely to

use this technology in most situations.

The .NET Framework uses assemblies as the fundamental unit for several purposes:

• Security

• Type Identity

• Reference Scope

• Versioning

• Deployment

Security

An assembly is the unit at which security permissions are requested and granted. Assemblies are also thelevel at which you establish identity and trust. The .NET Framework provides two mechanisms for this

level of assembly security: strong names and Signcode.exe. You can also manage security by specifyingthe level of trust for code from a particular site or zone.

Signing an assembly with a strong name adds public key encryption to the assembly. This ensures nameuniqueness and prevents substituting another assembly with the same name for the assembly that you

provided.

The signcode.exe tool embeds a digital certificate in the assembly. This allows users of the assembly toverify the identity of the assembly's developer by using a public or private trust hierarchy.

You can choose to use either strong names, Signcode.exe, or both, to strengthen the identity of yourassembly.

The common language runtime also uses internal hashing information, in conjunction with strong names

and signcode, to verify that the assembly being loaded has not been altered after it was built.

Type Identity

The identity of a type depends on the assembly where that type is defined. That is, if you define a type

named DataStore in one assembly, and a type named DataStore in another assembly, the .NETFramework can tell them apart because they are in two different assemblies. Of course you can't definetwo different types with the same name in the same assembly.

Reference Scope

The assembly is also the location of reference information in general. Each assembly contains informationon references in two directions:

• The assembly contains metadata that specifies the types and resources within the assembly that

are exposed to code outside of the assembly. For example, a particular assembly could expose a

public type named Customer with a public property named AccountBalance.

Page 4: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 4/20

• The assembly contains metadata specifying the other assemblies on which it depends. For

example, a particular assembly might specify that it depends on the System.Windows.Forms.dll

assembly.

VersioningEach assembly has a 128-bit version number that is presented as a set of four decimal pieces:Major.Minor.Build.Revision For example, an assembly might have the version number 3.5.0.126.Bydefault, an assembly will only use types from the exact same assembly (name and version number) that itwas built and tested with. That is, if you have an assembly that uses a type from version 1.0.0.2 of another assembly, it will (by default) not use the same type from version 1.0.0.4 of the other assembly.This use of both name and version to identify referenced assemblies helps avoid the "DLL Hell" problem of upgrades to one application breaking other applications.

Deployment

Assemblies are the natural unit of deployment. The Windows Installer Service 2.0 can install individualassemblies as part of a larger setup program. You can also deploy assemblies in other ways, including bya simple xcopy to the target system or via code download from a web site. When you start an application,it loads other assemblies as a unit as types and resources from those assemblies are needed.

The Assembly ManifestEvery assembly contains an assembly manifest, a set of metadata with information about the assembly.The assembly manifest contains these items:

The assembly name and version

• The culture or language the assembly supports (not required in all assemblies)

• The public key for any strong name assigned to the assembly (not required in all assemblies)

• A list of files in the assembly with hash information

• Information on exported types

• Information on referenced assemblies

The Global Assembly Cache

Assemblies can be either private or shared. By default, assemblies are private, and types contained withinthose assemblies are only available to applications in the same directory as the assembly. But everycomputer with the .NET Framework installed also has a global assembly cache (GAC) containingassemblies that are designed to be shared by multiple applications. There are three ways to add anassembly to the GAC:

• Install them with the Windows Installer 2.0

• Use the Gacutil.exe tool

• Drag and drop the assemblies to the cache with Windows Explorer

Note that in most cases you should plan to install assemblies to the GAC on end-user computers by usingthe Windows Installer. The gacutil.exe tool and the drag and drop method exist for use during thedevelopment cycle. You can view the contents of your global assembly cache by using Windows Explorerto navigate to the WINNT\assembly folder, as shown in Figure 1.

Assembly Info.vb

When you create a new project using Visual Basic .NET, one of the components of the project will be a filenamed AssemblyInfo.vb. This file contains all of the assembly attributes that describe the assembly. Tocharacterize your assembly, you should customize this information. You can edit the AssemblyInfo.vb file

 just like any other Visual Basic .NET source file. The default contents of this file look like this:

Page 5: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 5/20

' Version information for an assembly consists of the following

four values:

'

' Major Version

' Minor Version

' Build Number

' Revision

' You can specify all the values or you can default the Build

and Revision Numbers

' by using the '*' as shown below:

<Assembly: AssemblyVersion("1.0.*")>

pFigure 1. Viewing the Global Assembly Cache in Windows Explorer

Create the Class Library

Follow these steps to create the class library that will raise the events:

1. Open Microsoft Visual Studio® .NET, click Start, and then click New Project.

2. In the left pane tree view, select Visual Basic Project.

3. Select Class Library as the project template.

4. Set the name of the application to PowerLib and click OK.

5. In Solution Explorer, highlight the class called Class1.vb and rename it to Button.vb.

6. Select the code for Class1 in Button.vb (this be an empty class definition) and replace it with the

following code:

Public Class Button

Page 6: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 6/20

Private mfState As Boolean

Public Sub Toggle()

mfState = Not mfState

End Sub

Public Property State() As Boolean

Get

State = mfState

End Get

Set(ByVal Value As Boolean)

mfState = Value

End Set

End Property

End Class

Customize the Assembly

Follow these steps to customize the Assembly attributes:

1. In Solution Explorer, double-click the AssemblyInfo.vb file to open it in the code editor.

2. Select the first block of assembly attributes and modify them as follows:

<Assembly: AssemblyTitle("PowerPlant")>

<Assembly: AssemblyDescription("Power plant user interface")>

<Assembly: AssemblyCompany("Your Company")>

<Assembly: AssemblyProduct("PowerLib")>

<Assembly: AssemblyCopyright("Copyright 2002")>

<Assembly: AssemblyTrademark("")>

<Assembly: CLSCompliant(True)>

3. Select the version attribute and modify it as follows:

<Assembly: AssemblyVersion("1.0.0.0")>

Memory Management-:

Resource Allocation

The Microsoft .NET common language runtime requires that all resources be

allocated from the managed heap. Objects are automatically freed when they are nolonger needed by the application.

When a process is initialized, the runtime reserves a contiguous region of addressspace that initially has no storage allocated for it. This address space region is the

managed heap. The heap also maintains a pointer. This pointer indicates where the

Page 7: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 7/20

next object is to be allocated within the heap. Initially, the pointer is set to the baseaddress of the reserved address space region.

An application creates an object using the new operator. This operator first makes

sure that the bytes required by the new object fit in the reserved region (committingstorage if necessary). If the object fits, then pointer points to the object in the heap,

this object's constructor is called, and the new operator returns the address of theobject.

Above fig shows a managed heap consisting of three objects: A, B, and C. The nextobject to be allocated will be placed where NextObjPtr points (immediately after

object C).

When an application calls the new operator to create an object, there may not beenough address space left in the region to allocate to the object. The heap detects

this by adding the size of the new object to NextObjPtr. If NextObjPtr is beyond theend of the address space region, then the heap is full and a collection must be

performed.

In reality, a collection occurs when generation 0 is completely full. Briefly, a

generation is a mechanism implemented by the garbage collector in order to improveperformance. The idea is that newly created objects are part of a young generation,

and objects created early in the application's lifecycle are in an old generation.Separating objects into generations can allow the garbage collector to collect specific

generations instead of collecting all objects in the managed heap.

The Garbage Collection Algorithm

The garbage collector checks to see if there are any objects in the heap that are no

longer being used by the application. If such objects exist, then the memory used bythese objects can be reclaimed. (If no more memory is available for the heap, thenthe new operator throws an OutOfMemoryException.)

Every application has a set of roots. Roots identify storage locations, which refer toobjects on the managed heap or to objects that are set to null. For example, all the

global and static object pointers in an application are considered part of theapplication's roots. In addition, any local variable/parameter object pointers on a

thread's stack are considered part of the application's roots. Finally, any CPU

Page 8: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 8/20

registers containing pointers to objects in the managed heap are also considered partof the application's roots. The list of active roots is maintained by the just-in-time

(JIT) compiler and common language runtime, and is made accessible to the garbagecollector's algorithm.

When the garbage collector starts running, it makes the assumption that all objects

in the heap are garbage. In other words, it assumes that none of the application'sroots refer to any objects in the heap. Now, the garbage collector starts walking theroots and building a graph of all objects reachable from the roots. For example, the

garbage collector may locate a global variable that points to an object in the heap.

Following fig shows a heap with several allocated objects where the application's

roots refer directly to objects A, C, D, and F. All of these objects become part of thegraph. When adding object D, the collector notices that this object refers to object H,

and object H is also added to the graph. The collector continues to walk through allreachable objects recursively.

Once this part of the graph is complete, the garbage collector checks the next root

and walks the objects again. As the garbage collector walks from object to object, if it attempts to add an object to the graph that it previously added, then the garbagecollector can stop walking down that path. This serves two purposes. First, it helps

performance significantly since it doesn't walk through a set of objects more than

once. Second, it prevents infinite loops should you have any circular linked lists of objects.

Once all the roots have been checked, the garbage collector's graph contains the set

of all objects that are somehow reachable from the application's roots; any objectsthat are not in the graph are not accessible by the application, and are therefore

considered garbage.

The garbage collector now walks through the heap linearly, looking for contiguous

blocks of garbage objects (now considered free space). The garbage collector thenshifts the non-garbage objects down in memory (using the standard memcpy

function), removing all of the gaps in the heap. Of course, moving the objects inmemory invalidates all pointers to the objects. So the garbage collector must modify

the application's roots so that the pointers point to the objects' new locations. Inaddition, if any object contains a pointer to another object, the garbage collector is

responsible for correcting these pointers as well.

Following fig shows the managed heap after a collection.

Page 9: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 9/20

After all the garbage has been identified, all the non-garbage has been compacted,and all the non-garbage pointers have been fixed-up, the NextObjPtr is positioned

 just after the last non-garbage object. At this point, the new operation is tried againand the resource requested by the application is successfully created.

GC generates a significant performance hit, and this is the major downside of using amanaged heap. However, keep in mind that GCs only occur when the heap is full

and, until then, the managed heap is significantly faster than a C-runtime heap. Theruntime's garbage collector also offers some optimizations using Generations that

greatly improve the performance of garbage collection.

You no longer have to implement any code that manages the lifetime of any

resources that your application uses. Now it is not possible to leak resources, sinceany resource not accessible from your application's roots can be collected at some

point. Also it is not possible to access a resource that is freed, since the resourcewon't be freed if it is reachable. If it's not reachable, then your application has no

way to access it.

Following code demonstrates how resources are allocated and managed:

class Application{

public static int Main(String[] args){

 // ArrayList object created in heap, myArray is now in rootArrayList myArray = new ArrayList();

 // Create 10000 objects in the heapfor (int x = 0; x < 10000; x++)

{myArray.Add(new Object()); // Object object created in heap

} // Right now, myArray is a root (on the thread's stack). So,

 // myArray is reachable and the 10000 objects it points to are also reachable.

Page 10: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 10/20

Console.WriteLine(myArray.Count); // After the last reference to myArray in the code, myArray is not a root.

 // Note that the method doesn't have to return, the JIT compiler knows // to make myArray not a root after the last reference to it in the code.

 // Since myArray is not a root, all 10001 objects are not reachable // and are considered garbage. However, the objects are not

 // collected until a GC is performed.}}

If GC is so great, you might be wondering why it isn't in ANSI C++. The reason is

that a garbage collector must be able to identify an application's roots and must alsobe able to find all object pointers. The problem with C++ is that it allows casting a

pointer from one type to another, and there's no way to know what a pointer refersto. In the common language runtime, the managed heap always knows the actual

type of an object, and the metadata information is used to determine whichmembers of an object refer to other objects.

Generations

One feature of the garbage collector that exists purely to improve performance iscalled generations. A generational garbage collector (also known as an ephemeral

garbage collector) makes the following assumptions:

• The newer an object is, the shorter its lifetime will be.

• The older an object is, the longer its lifetime will be.

• Newer objects tend to have strong relationships to each other and are

frequently accessed around the same time.

Compacting a portion of the heap is faster than compacting the whole heap.

When initialized, the managed heap contains no objects. Objects added to the heapare said to be in generation 0, as you can see in following fig. Stated simply, objects

in generation 0 are young objects that have never been examined by the garbagecollector.

Page 11: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 11/20

Now, if more objects are added to the heap, the heap fills and a garbage collectionmust occur. When the garbage collector analyzes the heap, it builds the graph of 

garbage (shown here in Green) and non-garbage objects. Any objects that survive

the collection are compacted into the left-most portion of the heap. These objectshave survived a collection, are older, and are now considered to be in generation 1.

Page 12: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 12/20

As even more objects are added to the heap, these new, young objects are placed in

generation 0. If generation 0 fills again, a GC is performed. This time, all objects ingeneration 1 that survive are compacted and considered to be in generation 2 (see

following fig). All survivors in generation 0 are now compacted and considered to bein generation 1. Generation 0 currently contains no objects, but all new objects will

go into generation 0.

Page 13: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 13/20

Currently, generation 2 is the highest generation supported by the runtime's garbage

collector. When future collections occur, any surviving objects currently in generation2 simply stay in generation 2.

Disadvantages of Win32 heap:

• Most heaps (like the C runtime heap) allocate objects wherever they find free

space. Therefore, if I create several objects consecutively, it is quite possiblethat these objects will be separated by megabytes of address space.

However, in the managed heap, allocating several objects consecutively

ensures that the objects are contiguous in memory.

• When memory is allocated from a Win32 heap, the heap must be examined to

find a block of memory that can satisfy the request. This is not required in

managed heap, since here objects are contiguous in memory.

• In Win32 heap, data structures that the heap maintains must be updated. The

managed heap, on the other hand, only needs to increment the heap pointer.

Finalization

The garbage collector offers an additional feature that you may want to takeadvantage of: finalization. Finalization allows a resource to gracefully clean up after

itself when it is being collected. By using finalization, a resource representing a file ornetwork connection is able to clean itself up properly when the garbage collector

decides to free the resource's memory.

Page 14: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 14/20

When the garbage collector detects that an object is garbage, the garbage collectorcalls the object's Finalize method (if it exists) and then the object's memory is

reclaimed. For example, let's say you have the following type (in C#):

public class BaseObj{

public BaseObj(){}

protected override void Finalize(){

 // Perform resource cleanup code here // Example: Close file/Close network connection

Console.WriteLine("In Finalize.");}

}

Now you can create an instance of this object by calling:

BaseObj bo = new BaseObj();

Some time in the future, the garbage collector will determine that this object is

garbage. When that happens, the garbage collector will see that the type has aFinalize method and will call the method, causing "In Finalize" to appear in the

console window and reclaiming the memory block used by this object.

Many developers who are used to programming in C++ draw an immediate

correlation between a destructor and the Finalize method. However, objectfinalization and destructors have very different semantics and it is best to forget

everything you know about destructors when thinking about finalization. Managedobjects never have destructors.

When designing a type it is best to avoid using a Finalize method. There are severalreasons for this:

• Finalizable objects get promoted to older generations, which increases

memory pressure and prevents the object's memory from being collected

when the garbage collector determines the object is garbage. In addition, allobjects referred to directly or indirectly by this object get promoted as well.

• Finalizable objects take longer to allocate.

• Forcing the garbage collector to execute a Finalize method can significantly

hurt performance. Remember, each object is finalized. So if I have an array of 10,000 objects, each object must have its Finalize method called.

• Finalizable objects may refer to other (non-finalizable) objects, prolonging

their lifetime unnecessarily. In fact, you might want to consider breaking a

type into two different types: a lightweight type with a Finalize method thatdoesn't refer to any other objects, and a separate type without a Finalize

method that does refer to other objects.

• You have no control over when the Finalize method will execute. The object

may hold on to resources until the next time the garbage collector runs.

Page 15: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 15/20

• When an application terminates, some objects are still reachable and will not

have their Finalize method called. This can happen if background threads are

using the objects or if objects are created during application shutdown orAppDomain unloading. In addition, by default, Finalize methods are not called

for unreachable objects when an application exits so that the application mayterminate quickly. Of course, all operating system resources will be reclaimed,

but any objects in the managed heap are not able to clean up gracefully. Youcan change this default behavior by calling the System.GC type's

RequestFinalizeOnShutdown method. However, you should use this methodwith care since calling it means that your type is controlling a policy for the

entire application.

• The runtime doesn't make any guarantees as to the order in which Finalize

methods are called. For example, let's say there is an object that contains apointer to an inner object. The garbage collector has detected that both

objects are garbage. Furthermore, say that the inner object's Finalize methodgets called first. Now, the outer object's Finalize method is allowed to access

the inner object and call methods on it, but the inner object has beenfinalized and the results may be unpredictable. For this reason, it is strongly

recommended that Finalize methods not access any inner, member objects.

If you determine that your type must implement a Finalize method, then make sure

the code executes as quickly as possible. Avoid all actions that would block the

Finalize method, including any thread synchronization operations. Also, if you let anyexceptions escape the Finalize method, the system just assumes that the Finalize

method returned and continues calling other objects' Finalize methods.

When the compiler generates code for a constructor, the compiler automaticallyinserts a call to the base type's constructor. Likewise, when a C++ compiler

generates code for a destructor, the compiler automatically inserts a call to the basetype's destructor. Finalize methods are different from destructors. The compiler has

no special knowledge about a Finalize method, so the compiler does not

automatically generate code to call a base type's Finalize method. If you want thisbehavior-and frequently you do-then you must explicitly call the base type's Finalizemethod from your type's Finalize method:

public class BaseObj{

public BaseObj(){

}protected override void Finalize()

{

Console.WriteLine("In Finalize.");

base.Finalize(); // Call base type's Finalize}}

Note that you'll usually call the base type's Finalize method as the last statement in

the derived type's Finalize method. This keeps the base object alive as long aspossible. Since calling a base type Finalize method is common, C# has a syntax that

simplifies your work. In C#, the following code:

Page 16: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 16/20

class MyObject{

MyObject(){

}}

causes the compiler to generate this code:

class MyObject{

protected override void Finalize(){

base.Finalize();}

}

Note that this C# syntax looks identical to the C++ language's syntax for defining a

destructor. But remember, C# doesn't support destructors. Don't let the identicalsyntax fool you.

Finalization Internals

When an application creates a new object, the new operator allocates the memory

from the heap. If the object's type contains a Finalize method, then a pointer to theobject is placed on the finalization queue. The finalization queue is an internal data

structure controlled by the garbage collector. Each entry in the queue points to anobject that should have its Finalize method called before the object's memory can be

reclaimed.

Following fig shows a heap containing several objects. Some of these objects are

reachable from the application's roots, and some are not. When objects C, E, F, I,and J were created, the system detected that these objects had Finalize methods and

pointers to these objects were added to the finalization queue.

Page 17: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 17/20

When a GC occurs, objects B, E, G, H, I, and J are determined to be garbage. The

garbage collector scans the finalization queue looking for pointers to these objects.

When a pointer is found, the pointer is removed from the finalization queue and

appended to the freachable queue (pronounced "F-reachable"). The freachable queueis another internal data structure controlled by the garbage collector. Each pointer in

the freachable queue identifies an object that is ready to have its Finalize methodcalled.

After the collection, the managed heap looks like following fig. Here, you see that thememory occupied by objects B, G, and H has been reclaimed because these objects

did not have a Finalize method that needed to be called. However, the memoryoccupied by objects E, I, and J could not be reclaimed because their Finalize method

has not been called yet.

Page 18: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 18/20

There is a special runtime thread dedicated to calling Finalize methods. When the

freachable queue is empty (which is usually the case), this thread sleeps. But whenentries appear, this thread wakes, removes each entry from the queue, and calls

each object's Finalize method. Because of this, you should not execute any code in a

Finalize method that makes any assumption about the thread that's executing thecode. For example, avoid accessing thread local storage in the Finalize method.

The interaction of the finalization queue and the freachable queue is quitefascinating. First, let me tell you how the freachable queue got its name. The f is

obvious and stands for finalization; every entry in the freachable queue should have

its Finalize method called. The "reachable" part of the name means that the objectsare reachable. To put it another way, the freachable queue is considered to be a root

 just like global and static variables are roots. Therefore, if an object is on thefreachable queue, then the object is reachable and is not garbage.

In short, when an object is not reachable, the garbage collector considers the object

garbage. Then, when the garbage collector moves an object's entry from thefinalization queue to the freachable queue, the object is no longer consideredgarbage and its memory is not reclaimed. At this point, the garbage collector has

finished identifying garbage. Some of the objects identified as garbage have beenreclassified as not garbage. The garbage collector compacts the reclaimable memory

and the special runtime thread empties the freachable queue, executing eachobject's Finalize method.

Page 19: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 19/20

The next time the garbage collector is invoked, it sees that the finalized objects aretruly garbage, since the application's roots don't point to it and the freachable queue

no longer points to it. Now the memory for the object is simply reclaimed. Theimportant thing to understand here is that two GCs are required to reclaim memory

used by objects that require finalization. In reality, more than two collections may benecessary since the objects could get promoted to an older generation. Above fig

shows what the managed heap looks like after the second GC.

Dispose Method

Use this method to close or release unmanaged resources such as files, streams, andhandles held by an instance of the class that implements this interface. This method

is, by convention, used for all tasks associated with freeing resources held by anobject, or preparing an object for reuse.When implementing this method, objects

must seek to ensure that all held resources are freed by propagating the call throughthe containment hierarchy. For example, if an object A allocates an object B, and

object B allocates an object C, then A's Dispose implementation must call Dispose on

B, which must in turn call Dispose on C. Objects must also call the Dispose methodof their base class if the base class implements IDisposable.

If an object's Dispose method is called more than once, the object must ignore all

calls after the first one. The object must not throw an exception if its Disposemethod is called multiple times. Dispose can throw an exception if an error occurs

because a resource has already been freed and Dispose had not been calledpreviously.Because the Dispose method must be called explicitly, objects that

implement IDisposable must also implement a finalizer to handle freeing resourceswhen Dispose is not called. By default, the garbage collector will automatically call an

object's finalizer prior to reclaiming its memory. However, once the Dispose method

Page 20: Net Framework,Memory Management

7/28/2019 Net Framework,Memory Management

http://slidepdf.com/reader/full/net-frameworkmemory-management 20/20

has been called, it is typically unnecessary for the garbage collector to call thedisposed object's finalizer. To prevent automatic finalization, Dispose

implementations can call the GC.SuppressFinalize method.

Direct Control with System.GC

The System.GC type allows your application some direct control over the garbagecollector. You can query the maximum generation supported by the managed heap

by reading the GC.MaxGeneration property. Currently, the GC.MaxGenerationproperty always returns 2.

It is also possible to force the garbage collector to perform a collection by calling oneof the two methods shown here:

void GC.Collect(Int32 Generation)void GC.Collect()

The first method allows you to specify which generation to collect. You may pass any

integer from 0 to GC.MaxGeneration, inclusive. Passing 0 causes generation 0 to becollected; passing 1 cause generation 1 and 0 to be collected; and passing 2 causesgeneration 2, 1, and 0 to be collected. The version of the Collect method that takes

no parameters forces a full collection of all generations and is equivalent to calling:

GC.Collect(GC.MaxGeneration);