处置后交易状态的判断

Determining the status of Transaction after disposal

我想确定交易是否已经完成,根据结果,我想在另一个线程中做其他事情。

考虑以下 TransactionScope:

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

    Scope.Complete();
}

现在,在另一个 class 中,在一个单独的线程中,我正在查看具有类似事务的对象列表:

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 处理前跟踪每个事务的状态?

我相信我已经找到了利用 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"
            }
        }
    }
}