C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Object Lifetime In .Net - Part 1


Posted Date: 10 Oct 2009    Resource Type: Articles    Category: .NET Framework
Author: Naison Garvasis PekkattilMember Level: Silver    
Rating: 1 out of 5Points: 5



Object Lifetime In .Net



The common language runtime's garbage collector manages the allocation and release of memory for an application. C# programmers never directly deallocate a managed object from memory. Rather, .NET objects are allocated onto a region of memory termed the managed heap, where they will be automatically destroyed by the garbage collector “sometime in the future.”

When a new process is initilized, the runtime reserves a contiguous region of address space for the process. This reserved address space is called the managed heap. The managed heap maintains a pointer to the address where the next object in the heap will be allocated. Initially, this pointer is set to the managed heap's base address.

Now let us explore how the garbage collector allocates and releases memory. Consider the below mentioned class:


public class Person
{
string Name;
string Address;
public Person(string name, string address)
{
Name = name ;
Address = address;
}
}


After defining the class, any number of objects can be allocated in the managed heap using the C# “new” keyword. The new keyword returns a reference to the object on the heap, not the actual object itself. This reference variable is stored on the stack for further use in the application.
In order to invoke the members of the object, C# dot operator is applied to the stored reference:


static void Main(string[] args)
{
// Create a new object of person class
Person person = new Person("Bill", "Gates", "Microsoft");
// Invoke the member of the object using C# dot perator “.”
Console.WriteLine(person.ToString());
}



The Common Intermediate Language (CIL) of “new”


When the C# compiler encounters the new keyword, it will emit a CIL “newobj” instruction into the method implementation.

If we compile the above code and investigate the resulting assembly using ildasm.exe, following CIL statements can be found within the Main() method:


.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 18 (0x12)
.maxstack 3
.locals init ([0] class Person person)
IL_0000: nop
IL_0001: ldstr "Bill Gates"
IL_0006: ldstr "Microsoft"
IL_000b: newobj instance void Person::.ctor(string, string)
IL_0010: stloc.0
IL_0011: ret
} // end of method Program::Main


The newobj instruction informs the CLR to perform the following:

• Calculate the total amount of memory required for the object to be allocated

• Examine the managed heap to ensure that there is enough room to host the object to be allocated

• If enough room is available, allocate a new instance of the class associated with ctor and initialize all the fields in the new instance to 0 or null references as appropriate

• Invoke the constructor with the given arguments along with the newly created instance

• After the constructor has been called, reference of the initialized object is pushed on the stack

• Finally, before returning the reference to the caller, advance the next object pointer to point to the next available slot on the managed heap.


Note: ctor is a metadata token that indicates the name, class and signature of the constructor to be called.

As the application is busy allocating objects, the space on the managed heap may eventually become full. When processing the newobj instruction, if the CLR determines that the managed heap does not have sufficient memory to allocate the requested type, it will perform a garbage collection in an attempt to free up memory.

To reclaim space, the garbage collector collects objects that are no longer reachable. An object is no longer reachable when there are no references to it, all references are set to null, or all references to it are from other objects that can be collected as part of the current collection cycle.

In our example, once the Main() method call completes, the “person” reference is no longer reachable, and the associated Person object is a candidate for garbage collection.

When a collection occurs, the reachable objects are traced and marked as the trace proceeds. The garbage collector reclaims space by moving reachable objects into the contiguous space and reclaiming the memory used by the unreachable objects. Any object that survives the collection is promoted to the next generation.

Generations


To optimize the performance of the garbage collector, the managed heap is divided into three generations: 0, 1, and 2:

Generation 0 (Gen 0). This consists of newly created objects. Gen 0 is collected frequently to ensure that short-lived objects are quickly cleaned up. Those objects that survive a Gen 0 collection are promoted to Generation 1.

Generation 1 (Gen 1). This is collected less frequently than Gen 0 and contains
longer-lived objects that were promoted from Gen 0.

Generation 2 (Gen 2). This contains objects promoted from Gen 1 (which means it contains the longest-lived objects) and is collected even less frequently. The general strategy of the garbage collector is to collect and move longer-lived objects less frequently.

We will explore the generations in depth and also the members provided by System.GC class in Part 2 of this article.





Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Objects  .  Newobj  .  New  .  Lifetime  .  Generation  .  Garbage Collection  .  Collection  .  Collect  .  Class  .  Allocation  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Drag Drop in window form using c#.net
Previous Resource: System Net Mail
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use