TransactionScopeAsyncFlowOption.Enabled
和TransactionScopeOption.RequiresNew
+相关交易之间有什么区别?
我要实现的目标是在3个单独的线程中运行3个async
任务,而所有任务都在事务中。由于任务正在执行跨数据库操作,因此无法使用IDbTransaction
。我创建了2个可能的实现示例:
使用TransactionScopeAsyncFlowOption.Enabled
:
try
{
using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
List<System.Threading.Tasks.Task> tasks = new List<System.Threading.Tasks.Task>();
System.Threading.Tasks.Task t1 = new System.Threading.Tasks.Task(() => DoSomething1());
t1.Start();
tasks.Add(t1);
System.Threading.Tasks.Task t2 = new System.Threading.Tasks.Task(() => DoSomething2());
t2.Start();
tasks.Add(t2);
System.Threading.Tasks.Task t3 = new System.Threading.Tasks.Task(() => DoSomething3());
t3.Start();
tasks.Add(t3);
System.Threading.Tasks.Task.WaitAll(tasks.ToArray());
scope.Complete();
}
}
catch (Exception ex)
{
return ex.Message;
}
使用依存交易:
try
{
using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
{
Thread t1 = new Thread(p =>
{
DependentTransaction dTrans = (DependentTransaction)p;
try
{
using (TransactionScope childTrans = new TransactionScope(dTrans))
{
DoSomething1();
childTrans.Complete();
}
dTrans.Complete();
}
catch (Exception ex)
{
dTrans.Rollback(ex);
}
});
Thread t2 = new Thread(delegate(Object p)
{
DependentTransaction dTrans = (DependentTransaction)p;
try
{
using (TransactionScope childTrans = new TransactionScope(dTrans))
{
DoSomething2();
childTrans.Complete();
}
dTrans.Complete();
}
catch (Exception ex)
{
dTrans.Rollback(ex);
}
});
Thread t3 = new Thread(delegate(Object p)
{
DependentTransaction dTrans = (DependentTransaction) p;
try
{
using (TransactionScope childTrans = new TransactionScope(dTrans))
{
DoSomething3();
childTrans.Complete();
}
dTrans.Complete();
}
catch (Exception ex)
{
dTrans.Rollback(ex);
}
});
t1.Start(Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
t2.Start(Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
t3.Start(Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
t1.Join();
t2.Join();
t3.Join();
trans.Complete();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
我尝试在线查找更多信息,但仍然无法理解哪种方法更好,有什么区别?