Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of the TransactionScope in C#

My application has been enabled transaction scope. The below code has been used to activate the Scope, it was activated for one hour. However, It has been ended in 10 mins.

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,TimeSpan.FromHours(1)))
{
   // my code goes here.
}

What is the strange behavior? why doesn't it live up to one hour of life time?

like image 894
Smaug Avatar asked Feb 17 '23 23:02

Smaug


2 Answers

You have to extend the default transaction timeout in your app.config (or web.config):

<configuration>
 <system.transactions>
  <defaultSettings timeout="00:03:00" />
 </system.transactions>
</configuration>

You'll also have to change the configuration at the machine level, i.e. you'll have to edit the machine.config file too. The default maximum transaction timeout is 10 minutes at the machine level.

For example, I've added at the end of my machine.config file the following XML:

  <system.transactions>
    <machineSettings maxTimeout="100.23:59:59" />
  </system.transactions>

The machine.config file is located in the C:\Windows\Microsoft.NET\Framework\[framework version]\Config directory.

like image 86
ken2k Avatar answered Feb 23 '23 06:02

ken2k


TransactionScope has a default maximum timeout of 10 minutes. If you create it with larger timeout it will silently reduce it to 10 mins anyway. It is a quite surprising behavior, but code does exactly that:

public TransactionScope(TransactionScopeOption scopeOption, TimeSpan scopeTimeout)
{
     ...
     timeout = TransactionManager.ValidateTimeout(scopeTimeout);
     ...
}

And ValidateTimeout reduces it to TransactionManager.MaximumTimeout

internal static TimeSpan ValidateTimeout(TimeSpan transactionTimeout)
{
    ...
    if (TransactionManager.MaximumTimeout != TimeSpan.Zero && (transactionTimeout > TransactionManager.MaximumTimeout || transactionTimeout == TimeSpan.Zero))
    {
        return TransactionManager.MaximumTimeout;
    }
    return transactionTimeout;
}
like image 35
alex Avatar answered Feb 23 '23 07:02

alex