确定处置后交易状态



我正在尝试确定交易是否已经完成,并且取决于结果,我想在另一个线程中做其他事情。

考虑以下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;
            }
        }
    }
}

当我在构造函数中创建新操作时,我将CurrentransAction设置为操作:

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

问题是,到另一个线程处理操作时,currentTransAction已处理,投掷系统。

在处理之前,我如何在操作中跟踪每个交易的状态?

我相信我已经通过交易找到了解决方案。

我使用以下代码将委派分配给事件:

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"
            }
        }
    }
}

最新更新