众所周知,根据这个答案,TransactionScope的maxTimeout是在machine.config中定义的。
那么,原因是什么呢?为什么我们不能在app.config(web.config)或代码中覆盖它?
众所周知,根据这个答案,TransactionScope的maxTimeout是在machine.config中定义的。
那么,原因是什么呢?为什么我们不能在app.config(web.config)或代码中覆盖它?
为什么TransactionScope的超时定义在machine.config文件中?
为什么我们不能在app.config(web.config)或者代码中覆盖它?
1. 在web.config / app.config文件中进行覆盖:在machine.config文件中,在“system.transactions”节组节点下,在“machineSettings”节节点中,有一个名为‘allowExeDefinition’的属性,默认值为“MachineOnly”。将此值更改为“MachineToApplication”。这允许您添加以下内容到应用程序的web.config并覆盖机器范围设置:
<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));
机器配置文件的路径
%windir%\Microsoft.NET\Framework[版本]\config\machine.config
%windir%\Microsoft.NET\Framework64[版本]\config\machine.config
s_cachedMaxTimeout
和 s_maximumTimeout
。 - wodzu
maxTimeout
限制需要作为机器级别的设置,而不是应用程序级别的设置,因为事务范围可以调节应用程序之间的交易。如果两个应用程序为maxTimeout
提供了不同的设置,则会产生混淆,不知道应该使用哪个限制。 - Sergey Kalinichenko