Dot-Net

TransactionScopeOption - 必需或 RequiresNew

  • September 29, 2021

我目前對 TransactionScope 對象的建構子感到困惑。

假設我網站的使用者可以訂購產品。在送出他們的請求後,我對目前剩餘數量進行驗證,如果仍然大於零,我執行請求。然後,最後我減少目前剩餘的數量。

整個過程在一個事務中,使用 .NET transactionScope。

在閱讀了幾篇關於 .NET transactionScope 對象的文章之後,我現在對用於 transactionScope 的建構子的 TransactionScopeOption 的值有些困惑。

以下哪一項更適合上述情況:

public void ProcessRequest()  
{  
    TransactionOptions transactionOptions = new TransactionOptions();  
    transactionOptions.IsolationLevel = IsolationLevel.Serializable;  
    using (TransactionScope currentScope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions)) {  
     // DB Query to verify if quantity is still greater than zero  
     // DB Query to request and decrement quantity 
     currentScope.Complete();
    }  
}  

要麼

public void ProcessRequest()  
{  
    TransactionOptions transactionOptions = new TransactionOptions();  
    transactionOptions.IsolationLevel = IsolationLevel.Serializable;  
    using (TransactionScope currentScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) {  
     // DB Query to verify if quantity is still greater than zero  
     // DB Query to request and decrement quantity 
     currentScope.Complete();
    }  
}  

請注意,以上只是對我的實際問題的過度簡化。對於這種情況,我只對了解 TransactionScopeOption (RequiresNewRequired )的正確值感興趣。

感謝回复。

ProcessRequest 如果另一個方法在另一個事務中呼叫,這取決於您想要發生的情況:

public void SomeOtherMethod() {
   using (TransactionScope ts = new TransactionScope()) {
       // Another DB action
       ProcessRequest();
       // Yet another DB action
   }
}

如果要ProcessRequest使用創建的事務SomeOtherMethod,請使用TransactionScope.Required. 這是預設設置(當您呼叫它時它仍然會創建一個事務,而無需在呼叫堆棧上創建另一個事務範圍)。

如果您希望它強制此方法始終使用其自己的(新)事務,請使用TransactionScope,RequiresNew.

引用自:https://stackoverflow.com/questions/4629245