Cross-AppDomain调用后,为什么Transaction.Current变为空?

时间:2017-10-04 16:34:36

标签: .net appdomain remoting transactionscope system.transactions

考虑以下小程序,只需创建TransactionScope,打印Transaction.Current,在另一个AppDomain中调用方法(需要一段时间才能执行),然后在返回时打印Transaction.Current

using System;

using System.Linq;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Transactions;

namespace TransactionScopeFlowTest
{
   class Program
   {
      static void Main(string[] args)
      {
         // These times are just to generate the error faster. Normally the initial lease is 5 minutes, meaning the method call
         // would have to take 5 minutes to occur, so we speed it up here for demonstration purposes.
         LifetimeServices.LeaseManagerPollTime = TimeSpan.FromSeconds(1);
         LifetimeServices.LeaseTime = TimeSpan.FromSeconds(1);
         LifetimeServices.RenewOnCallTime = TimeSpan.FromSeconds(1);

         AppDomain domain = AppDomain.CreateDomain("Temp", null, AppDomain.CurrentDomain.SetupInformation);

         using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
         {
            Console.WriteLine($"Transaction Before Call = {Transaction.Current?.TransactionInformation?.LocalIdentifier?.ToString() ?? "<null>"}");
            domain.DoCallBack(AppDomainCallback);
            Console.WriteLine($"Transaction After Call = {Transaction.Current?.TransactionInformation?.LocalIdentifier?.ToString() ?? "<null>"}");
            scope.Complete();
         }

         AppDomain.Unload(domain);
      }

      public static void AppDomainCallback()
      {
         Thread.Sleep(3000);
      }
   }
}

很意外,该程序生成以下输出:

Transaction Before Call = 1f980219-2583-4796-8d6d-256a6f100698:1
Transaction After Call = <null>

如果我将TransactionScopeAsyncFlowOption的{​​{1}}更改为TransactionScope,则会在通话结束后保留​​交易。

我怀疑跨越逻辑上下文的事务范围流是由CallContext处理的,它通过远程调用传播,并且使用的密钥继承TransactionScopeAsyncFlowOption.Suppress,因为它们未注册任何MarshalByRefObject ,代理将在初始租约时间后断开连接。然后,一旦我们从调用返回,逻辑调用上下文就会与原始内容合并,这意味着事务不再存在。

我正在寻找绕过这个问题的方法,如果这被认为是.NET中的错误?

0 个答案:

没有答案