March 14, 2011

ASP.NET Performance Tip3 - Use using key word

The using keyword is basically a try - finally block, without a catch , where IDisposable.Dispose() is called in the finally .

Using block defines a scope, outside of which an object or objects will be disposed.

Use using keyword for the objects that  hold any resources other than managed memory.  For Example like files, sockets, database connections, or even GDI drawing handles.

We should  be using "using" whenever the class implements IDisposable. So use of using keyword will always help to avoid Garbage Collection call or explicitly calling garbage collector to

destroy objects.

For example

using(Dataset ds = new Dataset())

We do not need to worry about destroying objects once the job is done. Garbage Collector will take care of it.

using(ClassName x = new ClassName())

     ...use x here...


This will automatically remove the resources occupied by the obejct x.

Another Example while working with database objects :


using ( SqlConnection connection = new SqlConnection(connectionString) )


      SqlCommand cmd = new SqlCommand(commandString, connection);


      using (SqlDataReader reader = cmd.ExecuteReader())


         while (reader.Read())


    listBox1.Items.Add(reader[0].ToString() + ", " + reader[1].ToString());
But normally we use try ,catch and dispose objects explicitly in Finally. Why to do this when we have the job that will be done by CLR through GC with the help of using keyword. A "using" statement can be exited either when the end of the "using" statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement. Multiple Objects can be used with using statement as
using (Furniture chair = new Furniture(300, 400),
table = new Furniture(20, 100))
    // Use chair and table.

It is very important to know when to use what and implement best practices to achieve for performance , reliability

1 comment:

VC Internet Media said...

I am confident that by following your recommendations, I will not be
disappointed. I sincerely thank your efforts for making us knowledgeable people.
you have mentioned very useful and profitable message message for us .

Affiliate Marketing