C # using and try... finally statements

Source: Internet
Author: User
Tags mscorlib

In the past, we read that using is essentially a compiler that generates try {} finally {} to ensure that finally is always executed. I have never been too careful about this problem. Write todayCode, Encounter a paragraphProgramAs follows:

 

  1   Sqldatareader func ()
2 {
3
4 Using (Sqlconnection Conn = New Sqlconnection ())
5 {
6 Conn. open ();
7 Using (Sqlcommand comm = New Sqlcommand ())
8 {
9 // Some Initialization is omitted.
10   Sqldatareader Dr = Comm. executereader ();
11 Return Dr;
12 }
13
14 }
15 }

I thought that after return, using would not dispose the object. I did not expect the returned sqldatareader to close the connection. The following example is displayed in msdn:

 

 

Code

  The IL code generated using the using statement is actually a try, finally code block, releasing resources in the finally code block.

For example, a piece of code:

Using (Sqlconnection Conn = New Sqlconnection ())
{
Conn. open ();
Throw New Exception ( " Exception !! " ); // Can I recycle resources of the sqlconnection object after an exception is thrown?
}

The IL code can be:

// Code size 42 (0x2a)
. Maxstack 2
. Locals Init ([ 0 ] Class [System. Data] system. Data. sqlclient. sqlconnection Conn,
[ 1 ] Bool CS $ 4 $ 0000 )
Il_0000: NOP
Il_0001: newobj instance Void [System. Data] system. Data. sqlclient. sqlconnection:. ctor ()
Il_0006: stloc. 0
. Try
{
Il_0007: NOP
Il_0008: ldloc. 0
Il_0009: callvirt instance Void [System. Data] system. Data. Common. dbconnection: open ()
Il_000e: NOP
Il_000f: ldstr " Exception !! "
Il_0014: newobj instance Void [Mscorlib] system. Exception:. ctor ( String )
Il_0019: Throw
} // End. Try
Finally
{
Il_001a: ldloc. 0
Il_001b: ldnull
Il_001c: CEQ
Il_001e: stloc. 1
Il_001f: ldloc. 1
Il_0020: brtrue. s il_0029
Il_0022: ldloc. 0
Il_0023: callvirt instance Void [Mscorlib] system. idisposable: dispose ()
Il_0028: NOP
Il_0029: endfinally
} // End Handler

We can see that the dispose method of sqlconnection is called to release the resource.

This indicates that the using statement generates the resource release code no matter whether the return statement is in the block. Try .. The same is true for finally blocks. Finally blocks are executed first, and some possible return values in try are executed;

 

The following code confirms this point:

 

Code

  Class  Program
{
Static Void Main ( String [] ARGs)
{
Using (Usingtest UT = Testfunc ())
{

}

}

Static Usingtest testfunc ()
{
Try {
Usingtest UT = New Usingtest ();
Return Ut;
}
Finally
{

Console. writeline ( " Finally... " );

}
Return Null ; // The code here is always inaccessible, indicating that the return in try is actually executed immediately after finally execution.
}
}

Internal Class Usingtest: idisposable
{


Public Usingtest ()
{
Console. writeline ( " Constructing... " );
}
Public Void Dispose ()
{
Console. Write ( " Disposing ..... " );
}
}

Program output:

 

"Constructing ..."

"Finally ..."

"Disposing ....."

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.