2012-01-09 60 views
1

使用.net 2和ADO.NET。確定是否提交TransactionScope

有沒有辦法確定一個事務是否被提交?原因是我堅持使用我無法改變的遺留框架,並且可能或可能不是環境事務。有時環境事務已經被提交,導致下一次數據庫調用拋出異常,我需要知道它是否是。

任何指針都會很棒!

感謝

約翰

+1

發佈當前代碼庫的一些例子會有所幫助。 – Oded 2012-01-09 16:05:30

回答

2

檢查Transaction.Current.TransactionInformation.Status。如果它不是TransactionStatus.Active,則不應使用當前事務。

不言而喻,你應該檢查Transaction.Currentnull之前採取其狀態。

2

我已經找到了最有效地/捕獲此正確的最好方法是如下:

使用語句的TransactionScope內部,並調用範圍之前/完成()。

//Register for the transaction completed event for the current transaction 
Transaction.Current.TransactionCompleted += new TransactionCompletedEventHandler(Current_TransactionCompleted); 

然後創建事件處理函數如下:

/// <summary> 
/// Handles the TransactionCompleted event of the Current control. 
/// </summary> 
/// <param name="sender">The source of the event.</param> 
/// <param name="e">The <see cref="System.Transactions.TransactionEventArgs"/> instance containing the event data.</param> 
static void Current_TransactionCompleted(object sender, TransactionEventArgs e) 
{ 
    if (e.Transaction.TransactionInformation.Status == TransactionStatus.Committed) 
    { 
     /// Yay it's committed code goes here! 
    } 
} 

引述MSDN

「你可以爲這個事件而不是使用揮發性入伍以獲取交易結果的信息登記。傳遞給TransactionCompletedEventHandler委託的參數是一個Transaction實例,然後可以查詢特定實例的TransactionInformation屬性以獲取TransactionInformation的實例,其狀態屬性包含具有Committed或Aborted值的事務狀態。「

相關問題