Why does Transaction.Current become null after calling Cross-AppDomain?

Consider the following small program that simply creates TransactionScope, prints Transaction.Current, calls a method in another AppDomain (which takes some time to complete), and then returns Transaction.Currenton return.

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);
      }
   }
}

Quite unexpectedly, the program generates the following output:

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

If I change TransactionScopeAsyncFlowOptionctor from TransactionScopeto TransactionScopeAsyncFlowOption.Suppress, the transaction remains after the call.

, CallContext, , MarshalByRefObject, ISponsor, - . , , , .

, , ​​.NET?

+4

Source: https://habr.com/ru/post/1686904/


All Articles