讀書筆記:《亮劍 .Net》——System.Transactions 交易處理

來源:互聯網
上載者:User

使用System.Transactiions不需要考慮是簡單事務還是分散式交易。

在SQL Server 2005下.Net會建立一個Local Transaction,效能非常高。但是如果是SQL Server 2000,則會自動激發一個分散式交易,在效能上會受一些損失

 

using (TransactionScope ts = new TransactionScope())//使整個代碼塊成為事務性代碼
            {
                #region 在這裡編寫需要具備Transaction的代碼
                string msg = "";
                string conString = "data source=127.0.0.1;database=codematic;user id=sa;password=";
                SqlConnection myConnection = new SqlConnection(conString);
                myConnection.Open();
                SqlCommand myCommand = new SqlCommand();
                myCommand.Connection = myConnection;
                try
                {
                    myCommand.CommandText = "update P_Product set Name='電腦2' where Id=52";
                    myCommand.ExecuteNonQuery();
                    myCommand.CommandText = "update P_Product set Name='電腦3' where Id=53";
                    myCommand.ExecuteNonQuery();

                    msg = "成功!";
                }
                catch (Exception ex)
                {
                    msg = "失敗:" + ex.Message;
                }
                finally
                {
                    myConnection.Close();
                }
                #endregion

                ts.Complete();
                return msg;
            }

 

嵌套的交易處理

 

void RootMethod()
        {
            using (TransactionScope scope = new TransactionScope())
            {
                //作業碼
                SonMethod();
                scope.Complete();
            }
        }
        void SonMethod()
        {
            using (TransactionScope scope = new TransactionScope())
            {
                //作業碼
                scope.Complete();
            }
        }

 

事務範圍

如果想保留代碼部分執行的操作,並在失敗的情況下不希望終止環境事務使用TransactionScopeOption.Suppress

 

void MethodSuppress()
        {

            using (TransactionScope scope1 = new TransactionScope())
            {
                try
                {
                    //開始一個非事務範圍 
                    using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress))
                    {
                        //不受事務控制碼
                    }
                    //從這裡開始又迴歸交易處理
                }
                catch
                { }
            }
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.