C#中TransactionScope的使用方法和原理(摘)

來源:互聯網
上載者:User

標籤:

出自51CTO部落格:http://cnn237111.blog.51cto.com/2359144/1271600

 

在.net 1.1的時代,還沒有TransactionScope類,因此很多關於事務的處理,都交給了SqlTransaction和 SqlConnection,每個Transaction是基於每個Connection的。這種設計對於跨越多個程式集或者多個方法的事務行為來說,不 是非常好,需要把事務和資料庫連接作為參數傳入。

在.net 2.0後,TransactionScope類的出現,大大的簡化了事務的設計。範例程式碼如下:

1234567891011 static void Main(string[] args)        {            using (TransactionScope ts = new TransactionScope())            {                userBLL u = new userBLL();                TeacherBLL t = new TeacherBLL();                u.ADD();                t.ADD();                ts.Complete();            }        }

只 需要把需要事務包裹的邏輯塊寫在using (TransactionScope ts = new TransactionScope())中就可以了。從這種寫法可以看出,TransactionScope實現了IDispose介面。除非顯示調用 ts.Complete()方法。否則,系統不會自動認可這個事務。如果在代碼運行退出這個block後,還未調用Complete(),那麼事務自動回 滾了。在這個事務塊中,u.ADD()方法和t.ADD()方法內部都沒有用到任何事務類。

TransactionScope是基於當前線程的,在當前線程中,調用Transaction.Current方法可以看到當前事務的資訊。具體關於TransactionScope的使用方法,已經它的成員方法和屬性,可以查看MSDN。

TransactionScope類是可以嵌套使用,如果要嵌套使用,需要在嵌套事務塊中指定TransactionScopeOption參數。預設的這個參數為Required。

該參數的具體含義可以參考http://msdn.microsoft.com/zh-cn/library/system.transactions.transactionscopeoption(v=vs.80).aspx

比如下面代碼:

1234567891011121314151617 static void Main(string[] args)        {            using (TransactionScope ts = new TransactionScope())            {                Console.WriteLine(Transaction.Current.TransactionInformation.LocalIdentifier);                userBLL u = new userBLL();                TeacherBLL t = new TeacherBLL();                u.ADD();                using (TransactionScope ts2 = new TransactionScope(TransactionScopeOption.Required))                {                    Console.WriteLine(Transaction.Current.TransactionInformation.LocalIdentifier);                    t.ADD();                    ts2.Complete();                }               ts.Complete();            }        }

當嵌套類的TransactionScope的TransactionScopeOption為Required的時候,則可以看到如下結果,他們的事務的ID都是同一個。並且,只有當2個TransactionScope都complete的時候才能算真正成功。

 

如果把TransactionScopeOption設為RequiresNew,則嵌套的事務塊和外層的事務塊各自獨立,互不影響。

 

1234567891011121314151617 static void Main(string[] args)        {            using (TransactionScope ts = new TransactionScope())            {                Console.WriteLine(Transaction.Current.TransactionInformation.LocalIdentifier);                userBLL u = new userBLL();                TeacherBLL t = new TeacherBLL();                u.ADD();                using (TransactionScope ts2 = new TransactionScope(TransactionScopeOption.RequiresNew))                {                    Console.WriteLine(Transaction.Current.TransactionInformation.LocalIdentifier);                    t.ADD();                    ts2.Complete();                }              ts.Complete();            }        }

 

可以看到,他們的事務id是不一樣的。

TransactionScopeOption設為Suppress則為取消當前區塊的事務,一般很少使用。

對於多個不同伺服器之間的資料庫操作,TransactionScope依賴DTC(Distributed Transaction Coordinator)服務完成事務一致性。

但 是對於單一伺服器資料,TransactionScope的機制則比較複雜。主要用的的是線程靜態特性。線程靜態特性 ThreadStaticAttribute讓CLR知道,它標記的靜態欄位的存取是依賴當前線程,而獨立於其他線程的。既然儲存線上程靜態欄位中的資料 只對儲存該資料的同一線程中所啟動並執行代碼可見,那麼,可使用此類欄位將其他資料從一個方法傳遞到該第一個方法所調用的其他方法,而且完全不用擔心其他線程 會破壞它的工作。TransactionScope 會將當前的 Transaction 儲存到線程靜態欄位中。當稍後執行個體化 SqlCommand 時(在此 TransactionScope 從線程局部儲存中刪除之前),該 SqlCommand 會檢查線程靜態欄位以尋找現有 Transaction,如果存在則列入該 Transaction 中。通過這種方式,TransactionScope 和 SqlCommand 能夠協同工作,從而開發人員不必將 Transaction 顯示傳遞給 SqlCommand 對象。實際上,TransactionScope 和 SqlCommand 所使用的機制非常複雜。具體可以參考文章http://www.microsoft.com/china/MSDN/library/netFramework/netframework/NETMattersSep.mspx?mfr=true

Wrox出版的《Professional C# 4 and .NET 4》也有關於TransactionScope的一些使用方法的介紹。

C#中TransactionScope的使用方法和原理(摘)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.