Using Using

I have just completed reading a chapter in my book on performance. The books says to speed up performance on your web site you should use the using statement when opening connections. My question is how do you catch errors if you are using this as apposed to a try catch block.

thanks

Bryan 

-2
bryanlemmer
11/11/2007 11:10:45 PM
asp.net.getting-started 91979 articles. 2 followers. Follow

7 Replies
1758 Views

Similar Articles

[PageSpeed] 45

Why would you use it as an alternative to a try/catch statement. Couldn't you just do something like

  

public void UsingSomeMethod() {

try {
SomeMethod();
}
catch(SomeException e) {
/// do something useful
}
}

public void SomeMethod() {

using (Something) {
/// do something
}
}
 
2
JonLWright
11/11/2007 11:37:47 PM

public void SomeMethod()

 {
    using (Something)

    {

       try {}
       catch(SomeException e) {}
    }
}

2
subhendude
11/12/2007 4:34:34 AM

Hi,

So what is the actual benefit of using the using statement if you still have to put it in a try catch to catch errors, I thought that was the point of using using... to get away from the try catch which is apparently more of a memory chomper. Will it really speed up my apps then? The only benefit i can see it that you dont have to explicitly close your connection which would free up some memory there.

Bryan 

 

0
bryanlemmer
11/12/2007 8:50:13 AM

First of all there are two things, using Statement and using directive, I think you are referring to the 'using' statement.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources from http://msdn2.microsoft.com/en-us/library/yh598w02(VS.80).aspx

 

Now let me give a more precise example to explain this.. Imagine you opened an sql connection, and you forgot to call a dispose() on it i.e. to destroy the connection object, a lack of calling Dispose() on SqlConnection and SqlCommand objects and further imagine that the database code was not placed in try / finally blocks. 

SqlConnection cn = new SqlConnection(connectionString);
SqlCommand cm = new SqlCommand(commandString, cn);
cn.Open();
cm.ExecuteNonQuery();
cn.Close();


It sure is easy to follow :)

The problem is that SqlConnection and SqlCommand implement IDisposable, which means they could have unmanaged resources to cleanup and it is our job, the developers, to make sure Dispose() gets called on these classes after we are finished with them.  And, because an exception could be raised if the database is unavailable, we need to make sure Dispose() gets called even in the case of an exception.

Internally, this construct generates a try / finally around the object being allocated and calls Dispose() for you.  It saves you the hassle of manually creating the try / finally block and calling Dispose().

The new code would looking something like this:

using (SqlConnection cn = new SqlConnection(connectionString))
{
    using (SqlCommand cm = new SqlCommand(commandString, cn))
    {
        cn.Open();
        cm.ExecuteNonQuery();
    }
}

This is essentially equivalent to the following:

SqlConnection cn =  null;
SqlCommand cm = null;

try
{
    cn = new SqlConnection(connectionString);
    cm = new SqlCommand(commandString, cn);
    cn.Open();
    cm.ExecuteNonQuery();
}
finally
{
    if (null != cm);
        cm.Dispose();
    if (null != cn)
        cn.Dispose();
}

You may notice the lack of calling Close() on the SqlConnection class, cn.  Internally, Dispose() checks the status of the connection and closes it for you.  Therefore, technically you don't need to call Close() on the connection (cn) as Dispose() will do it for you. 

In addition, Dispose() destroys the connection string of the SqlConnection class.  Therefore, if you want to re-open the connection after calling Dispose() on cn, you will have to re-establish the connection string.  Not doing so will throw an exception by http://davidhayden.com/blog/dave/archive/2005/01/13/773.aspx


Please Mark Post that helped you as answer, also include a summary of what solved the problem as it helps others in similar situations
0
naturehermit
11/12/2007 9:20:22 AM

subhendude:

public void SomeMethod()

 {
    using (Something)

    {

       try {}
       catch(SomeException e) {}
    }
}

This code makes no sense!

"using" keyword defines a scope, outside of which the objects will be disposed. (The objects provided to the using statement must implement the IDisposable interface to call the Dispose method). Internally a try/finally block will be generated automatically around the object when you use it with the "using" statement and the Dispose method is called inside the finally block.

Thanks

More: http://msdn2.microsoft.com/en-us/library/3bwa4xa9.aspx

-Mark post(s) as "Answer" that helped you


Mark post(s) as "Answer" that helped you

Electronic Screw
Website||Blog||Dub@i.net
0
e_screw
11/12/2007 9:29:46 AM

naturehermit:
Now let me give a more precise example to explain this.. Imagine you opened an sql connection, and you forgot to call a dispose() on it i.e. to destroy the connection object, a lack of calling Dispose() on SqlConnection and SqlCommand objects and further imagine that the database code was not placed in try / finally blocks........

Code taken from David's blog. You should have attributed with the original entry http://davidhayden.com/blog/dave/archive/2005/01/13/773.aspx

Thanks


Mark post(s) as "Answer" that helped you

Electronic Screw
Website||Blog||Dub@i.net
0
e_screw
11/12/2007 9:38:33 AM

Hi,

I get all of this but i thought that there would be another construct to allow you to catch your error when using athe using statement. From your above example what i can see is that you still need to encapsulate your using code in a try catch to catch any potential error that may crop up.

I thought that the using statement was a substitute for a try catch block with its own error handling, but i was wrong. Thanks for the awesome explination. I will be adding this to my new projects.

Thanks A mill!

Bryan 

0
bryanlemmer
11/12/2007 9:44:28 AM
Reply:

Similar Artilces:

How to use net use?
Please can any one tell me how to use the dos command net use properly? I have read the help but can't seem to get it to work. Keep getting sytax error message. Thanks in advance. "Beowulf" <who-knows@no-one.com> wrote in message news:9krutk$puu$1@news.grc.com... > Please can any one tell me how to use the dos command net use properly? > > I have read the help but can't seem to get it to work. Keep getting sytax > error message. what are you trying to do? There are about 50 options to "net use" that do a ton of different thin...

How to get new web app to use .NET 2.0 on Win2K server using .NET 1.1 as default framework?
I have .net framework1.1 and 2.0 on our server running win2K. i have existing applications that uses asp.net 1.1, i also have a new app that use ASP.net 2.0.  how can i set my new .NET 2.0 app to point to asp.net 2.0 without messing up my existing .NET 1.1 apps? To specify the ASP .Net version fro a web application, do the followingIn IIS Manager select the web application -> Properties -> ASP.Net TabSelect  ASP.Net version you want to use for the applicationRegards,PrashantDont forget to click "Mark as Answer" on the post that helped you. But I am running Win2K...

Sending SMS using vb.net or C#.net using vb.net or c#.net
Hi  My requirement is I hav one csv file with these fields id,mobilenum,messgae,status.intiallu staus is 0. once i read the all fileds and take that mobile number.using tat mobile number  i need to send sms .after sending sms i shuld change status as 1 How to send sms thru coding (please dont provide any links.if it is provide also please give working links becox i checked codeproject .i didnt get any nice link. and also provide the how to update the status field im csv file   Thank ssandhya   To send SMS, you need some third party SMS providers. if you consul...

When to use ( and when to use ((?
I'm just not getting it. When do you use ( in a statement, when do you need to use ((, and is the space after either or both mandatory? For example, I coded this statement: if (( $_ eq $bad_guys_ip )) { more_stuff_here }; Why the two (( in an if? And why does it seem to not work when I miss the space after the ((? Thanx! Mark me as... /Corn-fused|Dense/ > I'm just not getting it. >=20 > When do you use ( in a statement, when do you need to use ((, and is > the space after either or both mandatory? >=20 > For example, I coded this sta...

How to use the arguments to use() in the package being used
Howdy,=20 The subject says it all believe it or not :) What I'm trying to figure out is how to pass an argument=20 (pragma I believe is the proper term) to use() and do=20 sonethign in the package based on it. I've looked at CGI.pm source but can't seem to track it down.=20 (Similar idea as to CGIs -oldstyle_urls -newstyel_urls) http://search.cpan.org/~lds/CGI.pm-3.04/CGI.pm#PRAGMAS What I'd like to do is something like this: # for old time's sake we'll just use our favorite module use Foo::Monkey qw(:Foo :Bar -doamazingthings); #then in Foo::Monkey...

Using jQuery
What are the advantages of using ScriptReference to include a jQuery source in my .NET pages as opposed to using the regular <script src='jquery.js'></script> method? Thanks.Ryan One advantage of the ScriptManager is that you can use application relative paths (e.g. ~/scripts/jquery.js).On a related note, if you're writing something that will be public facing, you might consider using Google's free CDN hosted version of jQuery. Encosia - ASP.NET, AJAX, and more.Latest article: How I handle JSON dates returned by ASP.NET AJAX  Thanks for the reply. I act...

Using Dot Net Nuke to maintain a site developed in VS.NET using C#
Hi,Does anyone know if there is a way to create a site using C# and Visual Studio.NET 2003, but then use Dot Net Nuke to allow non-technical users to add content to the site.  The current state of the site must be accessible in both VS.NET and DNN regardless of which application saved it last.  Also preferably I would like the language used to remain C# even when edited by the marketing staff, so that I can still maintain it myself using VS.NET.  Hope you understand what I mean. If this is not possible, I wonder if anyone knows what solution I am after.   Thanks in adv...

How to use HTTP protocol in .Net Remoting? Thanks and Regards,How to use Http protocol in .net Remoting
<>Hi,     <><>How to use HTTP protocol in .Net Remoting ? Is there any specific code bits requires for that ?    I am using TCP protocol it's working but when i change it to  HTTP it throwing an error like "Arugument null exception"<>  Could  anybody give samples for that? Thanks & Regards,Vijay Here is an example of HTTP remoting:http://msdn2.microsoft.com/en-us/library/system.runtime.remoting.channels.http.httpchannel.aspxCheers,       Kev...

Using .NET assembly through COM using cominterop
I have a .NET assembly that I call through COM in a classic ASP application using Cominterop.  It used to work fine, however, it's been some time and I've had to make a change and recompile it.  Unfortunately for me, I can't remember how I registered the thing to tell COM how to instantiate it, i.e running regsvr32 and passing the dll returns and error.  I have a .tlb file but I can't remember if I can use that to register the dll??  Hey it's been one busy couple of months!Need help. You could try PInvoke(platform Invoke) solution in this post.  Hope this help...

Use of Net Use command to map a drive
--____ETNOBHIDCKMBHAFMGEBY____ Content-Type: text/plain; charset=iso-8859-15 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline; modification-date="Sat, 28 Mar 2008 13:05:52 +0000" I'm trying to find the correct syntax to enable the mapping of a netware = drive from a batch file. We are trying to use a backup utility that logs = into a Windows XP machine remotely, maps the netware drives then backs up = the mapped drives. Finaly it will delete the maps and logout. Has anyone any experience of exactly using the net use command to map a = drive...

why to use 1)use CGI,2)use Strict ,3)use Carp in script
hi why we r using 1)use CGI, 2)use Strict, 3)use Carp in the begining of script sometimes. What is the use of it.Is the files CGI.pm,Strict.pm,Carp.pm default with PERL. Thnx __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com On Thu, 2004-11-04 at 09:31, supriya devburman wrote: > hi Hi > why we r using > 1)use CGI, We only use CGI when we want to use methods from that module (usually on web pages); see `perldoc CGI` for more information on what you...

used a c#.net to vb.net converter and am now getting a syntax error.
ok I used a cool utility at http://www.kamalpatel.net/ConvertCSharp2VB.aspx to convert some c#.net to vb.net and it spit out a bunch of code which almost works but I am getting a syntax error on this line Imports (StreamReader sr = Shadows Function)() As StreamReader(objResponse.GetResponseStream()) I tried it that way and also like Imports (StreamReader sr = Shadows Function)() As StreamReader(objResponse.GetResponseStream()) but either way gave the same error Compiler Error Message: BC30035: Syntax error. Source Error: Line 26: Line ...

Using a REST API using "Astoria" (with .NET Framework 3.5 and VS.NET 2008 SP1)
Hello! I'm really interested in learning how to work with the new .NET Framework 3.5 and VS.NET 2008 SP1 (still beta). Here is my question: I would like to use a REST API that is not made by me. I'm talking about the REST API of Community Server 2008 (www.communityserver.org). I've got the full specification of the API. They have it well documented and ready to go. It appears to be very easy to use, but... HOW? How to connect the web services with the new .NET 3.5 properly? The full specification can be read here: http://api.communityserver.org. I've successully used...

where can i get a complete tutorial that will get me seriously started on using the objectdatasource effectively
It looks like using the objectdatasource is the way to go. will some one point to a tutorial that will get me seriously started on using the objectdatasource effectively.--------------------------------------------------No Project Too Eazy.-------------------------------------------------- http://www.asp.net/learn/dataaccess/default.aspx?tabid=63Orhttp://www.imar.spaanjaars.com/QuickDocId.aspx?quickdoc=416 First one uses typed datasets, second one uses custom business objects.  Both excellent tutorials. Regards Mike [MVP - ASP/ASP.NET]My site...

Web resources about - Using Using - asp.net.getting-started

Charlie Sheen Back on HIV Meds After Experimental Drugs Failed–Actor to Become a Series Regular On ‘The ...
Charlie Sheen found himself in the hot seat when he agreed to appear on The Dr. Oz Show earlier in the week . Dr. Oz had tough questions ready ...

Indonesia says attack underlines emergence of Islamic State threat
By Randy Fabi and Fergus Jensen JAKARTA (Reuters) - Indonesia must strengthen its defenses against Islamic State and work with neighboring countries ...

U.S. to invest billions in self-driving cars
Self-driving cars got a financial shot in the arm from the federal government Thursday, but a new report shows the autonomous vehicles have safety ...

US Powerball: Tickets, results, winning numbers, live stream of lottery for Australians
ONE of the winners of the world record Powerball jackpot has been revealed as a California nurse who was given the ticket by her generous boss. ...

America Ferrera Explains Where Golden Globes Bit with Eva Longoria Came From!
America Ferrera strikes a pose as she attends the 2016 Winter TCA Tour to promote her new NBC show Superstore on Wednesday (January 13) in Pasadena, ...

Top 5 apps that will make OS X sysadmins' lives better
If you want to streamline your sysadmin work but you don't know where to begin, Jesus Vigo gets the ball rolling by highlighting five useful ...

Franchise Ensemble SAG Award? ‘Chicago’ Boss Dick Wolf Calls For Rule Change
Two decades ago, Dick Wolf helped change the rules of dramatic storytelling with the introduction of the first crossover between his Law & Order ...

Netflix plans to block VPNs out of Australia
Netflix has warned that it will be cracking down on customers using proxies or unblockers to access its global catalogue, because it wants to ...

Foursquare's new CEO to shift company focus beyond consumers
Foursquare gambled big two years ago when it split its app in two. Unfortunately, that hasn't worked out so well. Despite reinstating universal ...

Data Scientist Mansplains Manspreading
For years, it’s been thought that manspreading is a result of men needing room for their penises (peni?) to breathe. There’s an even better potential ...

Resources last updated: 1/15/2016 5:27:40 AM