Why use a using statement with a SqlTransaction?

前端 未结 9 1360
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 11:27

I\'ve been running into some problems concerning a SqlTransaction I\'m using in my code. During my Googling I see many people using a using statement with a SqlTransaction.<

相关标签:
9条回答
  • 2020-12-02 11:43

    The Using statement is shorthand for properly handling a resource. You can find more information at MSDN article on Using statement

    0 讨论(0)
  • 2020-12-02 11:44

    In addition to all that, it prettifies your code. Doesn't the 7 lines of code look better than the 14 lines? I breath a sign of relief every time I see a using block. It's like that little squirt of mist that comes out of that glad smelly thing. Mmm, I'm a pretty block of efficient code. Look at how well I manage memory and how pleasing I am to the eye.

    0 讨论(0)
  • 2020-12-02 11:55

    Essentially the using does the same thing that you are doing, except int a finally block instead of catching all exceptions:

    using (SqlConnection cn = new SqlConnection())
    {
         using (SqlTransaction tr = cn.BeginTransaction())
         {
          //some code
          tr.Commit();
         }
    }
    

    is the same as, just much less code :)

    {
        SqlConnection cn = null;
        try
        {
           cn = new SqlConnection();
           {
               SqlTransaction tr = null;
               try
               {
                   tr = cn.BeginTransaction())
    
                   //some code
                   tr.Commit();
                }
                finally
                {
                    if(tr != null && tr is IDisposable)
                    {
                        tr.Dispose();
                    }
                }
            }
        }
        finally
        {
            if(cn != null && cn is IDisposable)
            {
                cn.Dispose();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题