using System;
using System.Transactions;
namespace ConsoleApplication3
{
public class Program
{
public static void Main(string[] args)
{
var trans = new TransactionScope(TransactionScopeOption.RequiresNew);
try
{
if (!ProcessMessage(true))
{
MoveMessageToErrorQueue();
}
trans.Complete();
}
catch (Exception)
{
trans.Dispose();
}
}
private static bool ProcessMessage(bool throwError)
{
//write to database
var trans = new TransactionScope(TransactionScopeOption.Required);
try
{
if (throwError)
throw new Exception();
trans.Complete();
return true;
}
catch (Exception)
{
trans.Dispose();
}
return false;
}
private static void MoveMessageToErrorQueue()
{
var trans = new TransactionScope(TransactionScopeOption.Required);
trans.Complete();
}
}
}
如何使MoveMessageToErrorQueue方法中的事务范围在主事务中登记,而不是在ProcessMessage方法中的事务范围中?嵌套事务的TransactionScope
当它试图在MoveMessageToErrorQueue内部创建一个新的事务时,我得到一个异常,指出该事务已经被中止。
UPDATE
我得到同样的结果,如果我用一个CommittableTransaction
using System;
using System.Transactions;
namespace ConsoleApplication3
{
public class Program
{
public static void Main(string[] args)
{
using (var trans = new CommittableTransaction())
{
try
{
if (!ProcessMessage(trans, true))
{
MoveMessageToErrorQueue(trans);
}
trans.Commit();
}
catch (Exception)
{
trans.Rollback();
}
}
}
private static bool ProcessMessage(Transaction trans, bool throwError)
{
//write to database
var transScope = new TransactionScope(trans);
try
{
if (throwError)
throw new Exception();
transScope.Complete();
return true;
}
catch (Exception)
{
transScope.Dispose();
}
return false;
}
private static void MoveMessageToErrorQueue(Transaction trans)
{
var transScope = new TransactionScope(trans);
transScope.Complete();
}
}
}
基本上,如果在的ProcessMessage方法中的交易失败我希望能够仍然使用在同一根事务最后一种方法。
感谢您的任何帮助。
UPDATE 2
“在DTC交易(和使用该图案的交易),故障是致命的和直接的一个注定标志被设置:。它被设置”
这说明了一切。我认为这种行为是不同的。
看起来更像C# – cup
在原来的情况下,你可以通过复制构造函数将TransScope传递给MoveMessageToErrorQueue吗? – cup
嗨,感谢您的评论,但我没有关注你。 – Marco