Search code examples
c#entity-frameworktransactionstransactionscope

Transactionscope timeout max is only 10 mins


I am not able to modify the machine.config on the client

Is there any other way in nested transactions for them to last longer than 10 mins? does isolation level or any other option help in the timeout issue. My transaction within DoWork() is fine, I think it is the outer transaction that is timing out.

private void DoAllWork()
{
    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TransactionManager.MaximumTimeout))
    {
        DoWork();
        scope.Complete();   
    }
}
private void  DoWork()
{
    Foreach(Some long running loop)
    {   
        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TransactionManager.MaximumTimeout))
        {
            // Entity Framework queries / modification / Save Changes
            scope.Complete();   
        }
    }
}

Solution

  • I had the same issue . you need to change it in machine.config.These setting does not work . But changing machine.config is not good so I solved it like this .What I am doing is get the transaction Manager object at run time and updating its value and it works for me .

       public TransactionScope CreateTransactionScope(TimeSpan timeout)
        {
            SetTransactionManagerField("_cachedMaxTimeout", true);
            SetTransactionManagerField("_maximumTimeout", timeout);
    
              var transactionScopeOptions = new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadUncommitted,
                    Timeout = timeout
                };
    
            return new TransactionScope(TransactionScopeOption.RequiresNew, transactionScopeOptions);
        }
    
    
          private void SetTransactionManagerField(string fieldName, object value)
        {
            typeof(TransactionManager).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, value);
        }
    

    And I Use it like this

              using (var scope = CreateTransactionScope(TimeSpan.FromMinutes(50)))
                {
            // do something 
            scope.Complete();
    
    
            }
            catch (Exception e)
            {
                new Logger().LogException(e);
    
    
            }