Why would try/finally rather than a “using” statement help avoid a race condition?

后端 未结 4 1709
眼角桃花
眼角桃花 2020-11-29 07:29

This question relates to a comment in another posting here: Cancelling an Entity Framework Query

I will reproduce the code example from there for clarity:

         


        
4条回答
  •  有刺的猬
    2020-11-29 08:05

    Depending on whether you use using or explicitly try/finally you can have slightly different code using the sample code you will have

        AdventureWorks2008R2Entities entities = null;
        try // Don't use using because it can cause race condition
        {
            entities = new AdventureWorks2008R2Entities();
            ...
        } finally {
        } 
    

    substituting that with a using statement it could look like

       using(var entities = new AdventureWorks2008R2Entities()){
          ...
       }
    

    which accordig do §8.13 of the specification will be expanded to

        AdventureWorks2008R2Entities entities = new AdventureWorks2008R2Entities();
        try
        {
            ...
        } finally {
        } 
    

    Therefor the only real difference is that the assignment is not within the try/finally block but that has no consequence on which race conditions could occur (aside from thread abort inbetween the assignement and the try block as Hans also notes)

提交回复
热议问题