2017-03-09 81 views
0

我想確定交易是否已完成,並根據結果,我想在另一個線程中執行其他事情。確定處置後的交易狀態

考慮下面的TransactionScope:

using (TransactionScope scope = new TransactionScope()) 
{ 
    // Do stuff 

    Scope.Complete(); 
} 

現在,在另一個類,在一個單獨的線程,我會通過有類似的交易對象的列表:

private static void ProcessActions() 
{ 
    while(true) 
    { 
     action = pendingActions[0]; 
     if (action.CurrentTransaction == null || 
      action.CurrentTransaction.TransactionInformation.Status == TransactionStatus.Committed) 
     { 
      // Proceed to do things!! 
      remove = true; 
     } 
     else if (action.CurrentTransaction.TransactionInformation.Status == TransactionStatus.Aborted) 
     { 
      // Transaction has aborted. Remove this action from the list 
      remove = true; 
     } 

     if (remove) 
     { 
      lock (pendingActions) 
      { 
       pendingActions.Remove(action); 
       eventCount = pendingActions.Count; 
      } 
     } 
    } 
} 

我設置CurrentTransaction當我在構造函數中創建新動作時的動作:

public Action() 
{ 
    CurrentTransaction = System.Transactions.Transaction.Current; 
} 

問題在於,當其他線程正在處理操作時,action.CurrentTransaction被處置,拋出System.ObjectDisposedException。

如何在Action中處理每個事務的狀態?

+0

你想達到什麼目的? – VMAtm

+0

@VMAtm我只是想檢查每個動作的事務是否仍在處理,中止或提交,然後再繼續執行其他操作。我想我找到了一個解決方案。在下面檢查我的答案。 –

回答

2

我相信我找到了一個解決方案,利用Transaction.TransactionCompleted Event

我用下面的代碼爲委託分配給TransactionCompleted事件:

System.Transactions.Transaction.Current.TransactionCompleted += new TransactionCompletedEventHandler(Mother.Current_TransactionCompleted); 

在該方法中,我能夠通過我的行動進行迭代,並確定哪一個具有相應的原始交易。像這樣:

public static void Current_TransactionCompleted(object sender, TransactionEventArgs e) 
{ 
    var originatingTransaction = sender as System.Transactions.Transaction; 

    lock (pendingActions) 
    { 
     for (int i = pendingActions.Count - 1; i >= 0; i--) 
     { 
      var action = pendingActions[i]; 

      if (originatingTransaction.Equals(action.CurrentTransaction)) 
      { 
       var transactionStatus = e.Transaction.TransactionInformation.Status; 
       if (transactionStatus == TransactionStatus.Committed) 
       { 
        // Later in the code, I will do stuff if CurrentTransaction is null 
        action.CurrentTransaction = null; 
       } 
       else if (transactionStatus == TransactionStatus.Aborted) 
       { 
        // if It's aborted, I will remove this action 
        pendingActions.RemoveAt(i); 
       } 
       // I will skip processing any actions that still have a Transaction with the status of "Processing" 
      } 
     } 
    } 
}