簡體   English   中英

如果外部事務范圍未完成,內部事務范圍是否會回滾?

[英]Will an inner transaction scope roll back if the outer transaction scope doesn't complete?

我有兩個交易范圍,一個在另一個范圍內。 我很想知道內部事務范圍是否會在提交后回滾並且外部事務范圍未完成。

這取決於您啟動嵌套事務范圍的范圍選項。

如果您使用默認選項TransactionScopeOption.Required則嵌套范圍將與外部范圍在同一事務中登記,因此當外部范圍回滾時,內部范圍也將回滾,即使它已調用Complete

但是,如果您使用TransactionScopeOption.RequiresNew ,則嵌套范圍將開始其自己的事務並獨立於外部范圍完成它,因此即使外部范圍回滾,它也不會回滾。

如果您使用TransactionScopeOption.Suppress ,則嵌套范圍將不會參與外部事務並將以非事務方式完成,因此不會構成在外部事務回滾時將回滾的工作的一部分。

由於它們是嵌套的,所以內部事務將回滾。

這不是全部,取決於您如何創建嵌套事務,但默認情況下,它會回滾。

本文深入介紹了TransactionScope ,應該可以回答您的大部分問題。


分發與否無關緊要。

是的,你可以參考下面的代碼。 如果內部事務拋出錯誤,則以下代碼將回滾外部事務范圍,反之亦然。

   public bool rootMethod(){
          using (var transaction = new(TransactionScopeOption.RequiresNew))
           try{
           // your code here
           SomeController someController = new SomeController();
           var responseFromChildMethod = someController.childMethodWithTxn();

       // your logic here

       transaction.Complete();
       return true;
       }
       catch(Exception ex){
       transaction.Dispose();
       return false;
       }
    } 
}

SomeController.cs

public bool childMethodWithTxn(){
  using(var newTransaction =  new TransactionScope()){
    try{
      //your code here
      newTransaction.Complete();
      return true;
    }
    catch(Exception ex){
           newTransaction.Dispose();
           return false;
           }

  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM