[C #] [Tips] Revisited using statement

[C #] [Tips] Revisited using statement


Previous I probably describes what is using statement, it can be said simply using statement is try finally simple syntax,

But I have some friends thought that using statement will eat all exceptions (try catch finally grammar),

Previously on MSDN forums also have seen some users also supports this argument,

So I have to verify this using statement contained in the end if there is catch.

I use MSDN Van column is successfully compiled to IL agency code than using statement to see whether it contains the catch.

Font font2 = new Font("Arial", 10.0f);
using( font2 )
{
    bool isbold = font2.Bold;
}

THE

image

 Font font2 = new Font( "Arial", 10.0f );
            try
            {
                bool isbold = font2.Bold;
            }
            finally
            {
                if( font2 != null )
                    font2.Dispose ();
            }

 

THE 

image

Both versions can be seen in IL agency code almost exactly the same, but does not include the catch.

After a look at try catch finally IL intermediary code

 Font font2 = new Font( "Arial", 10.0f );
            try
            {
                bool isbold = font2.Bold;
            }
            catch( Exception ex )
            { 
            }
            finally
            {
                if( font2 != null )
                    font2.Dispose ();
            }

 

THE

image

Through intermediaries IL code we can really know the using statement does not contain a catch, so do not misunderstand the use of using stement will eat all exceptions.

Previous I also mentioned that if you want to catch them exceptions shall be added to their own try catch, we have to look at the C # compiler what kind of program output.

 Font font2 = new Font( "Arial", 10.0f );
            using( font2 )
            {
                try
                {
                    bool isbold = font2.Bold;
                }
                catch( Exception ex )
                {
                }
            }

 

image image

Use can be seen after using statement + try catch, just as with the try catch finally.

To add using statement Note:

1. Due to be hidden implementation of the Dispose , so the need for manual processing, if performed manually yourself Close (), Dispose (),

  CLR will only make once again a waste of resources, thereby affecting application performance.

reference

SQL Server Connection Pooling (ADO.NET)

Original: Large column  [C #] [Tips] Revisited using statement


Guess you like

Origin www.cnblogs.com/petewell/p/11489726.html