As we know from this answer, maxTimeout for TransactionScope is defined in machine.config.
So, what the reason? Why we can't override it in app.config (web.config) or just in code?
Why TransactionScope timeout is defined in machine.config?
Why we can't override it in app.config (web.config) or just in code?
1. Override in web.config / app.config file : - in machine.config file, under "system.transactions" section-group node, in "machineSettings" section node, there is attribute named 'allowExeDefinition' with default value = "MachineOnly". Change this value to "MachineToApplication". This allows one to add the following to an application's web.config and override the machine wide setting :
<system.transactions>
<machineSettings maxTimeout="00:20:00" />
</system.transactions>
Although this approach changes a machine wide setting, it does not change the machine wide maxtimeout for the machine. One will be able to retain whatever value is set for the maxTimeout and one will be able to set whatever value is fit for the specific application in the app.config. Thus, each app can override the machine wide maxTimeout setting and set its own maxTimeout.
2. Override in code :
It doesn't require modifying the machine.config, it doesn't open up other application to possible DOS situations and it circumvents any company policy. Below is the code that does this:
public static class TransactionManagerHelper
{
public static void OverrideMaximumTimeout(TimeSpan timeout)
{
//TransactionScope inherits a *maximum* timeout from Machine.config. There's
no way to override it from
//code unless you use reflection. Hence this code!
//TransactionManager._cachedMaxTimeout
var type = typeof(TransactionManager);
var cachedMaxTimeout = type.GetField("_cachedMaxTimeout",
BindingFlags.NonPublic | BindingFlags.Static);
cachedMaxTimeout.SetValue(null, true);
//TransactionManager._maximumTimeout
var maximumTimeout = type.GetField("_maximumTimeout", BindingFlags.NonPublic | BindingFlags.Static);
maximumTimeout.SetValue(null, timeout);
}
}
To use it call the following before creating the TransactionScope object:
TransactionManagerHelper.OverrideMaximumTimeout(TimeSpan.FromMinutes(5));
Path of Machine.config
%windir%\Microsoft.NET\Framework[version]\config\machine.config
%windir%\Microsoft.NET\Framework64[version]\config\machine.config
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With