Nested with statements - which will not be deleted

If I have code like this and an error occurs in the second using statement, will the dispose method on the first if not be called?

using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(cnstr)) { cn.Open(); using (SqlTransaction tran = cn.BeginTransaction(IsolationLevel.Serializable)) { 

- EDIT -

It is also better to write a Try / finally block or use a statement. The internal compiler will generate Try / finally to use the operator, but according to coding standards, which is better?

+6
source share
3 answers

No, both will be called. Just because an exception is thrown in an internal expression does not mean that the first is ignored.

The using statement is another syntax for:

 var iDisposableItem = new Item(); try { ...... } finally { iDisposableItem.Dispose(); } 

so in your example:

 var iDisposableItem = new Item(); try { var iDisposableItem2 = new Item(); try { throws exception } finally { iDisposableItem2 .Dispose(); } } finally { iDisposableItem.Dispose(); } 

Now, what should be noted and that you need to be careful is that everything that caused the first exception could cause problems with the external using statement when it calls Dispose() . An exception can cause (really any) an object to be in an error state, and a call to Dispose can lead to another other exception that "masks" the first. This is getting in WFC when using statements using : http://msdn.microsoft.com/en-us/library/aa355056.aspx

+11
source

The A using try/finally nothing more than try/finally , if the process is not forcibly terminated, your objects will be deleted correctly.

In other words, it is:

 using (Type1 x = new Type1()) { // a using (Type2 y = new Type2()) { // b } // c } 

Actually it looks like (this is simplified):

 Type1 x = new Type1(); try { // a Type2 y = new Type2(); try { // b } finally { y.Dispose(); } // c } finally { x.Dispose(); } 
+2
source

It will have both, and you can shorten it like:

 using (SqlConnection cn = new SqlConnection(cnstr), SqlTransaction tran = cn.BeginTransaction(IsolationLevel.Serializable)) { cn.Open(); } 
0
source

Source: https://habr.com/ru/post/888567/


All Articles