我正在尝试确定交易是否已经完成,并且根据结果,我想在另一个线程中做其他事情。
考虑以下TransactionScope:
public class Contact{
public String name;
public String email;
public Contact(String name,String email){
this.name=name;
this.email=email;
}
public boolean contains(String str){
return name.contains(str)|| email.contains(str);
}
@Override
public String toString() {
return name+"\n"+email;
}
}
现在,在另一个类中,在一个单独的线程中,我将浏览具有类似事务的对象列表:
using (TransactionScope scope = new TransactionScope())
{
// Do stuff
Scope.Complete();
}
当我在构造函数中创建一个新动作时,我为一个动作设置了CurrentTransaction:
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;
}
}
}
}
问题是,当其他线程正在处理动作时,处理action.CurrentTransaction,抛出System.ObjectDisposedException。
如何在处置之前跟踪每个事务的状态?
答案 0 :(得分: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"
}
}
}
}