代码改变世界

Transaction Manager Maximum Timeout

2013-07-31 12:43  Franz  阅读(540)  评论(0编辑  收藏  举报

TransactionManager.MaximumTimeout是个只读的属性, 默认只有10分钟, 要想修改它必须通过machine.config来修改. 为了单个应用而去修改这个值是不合适的. stackoverflow.com上是给出的解释都是修改machine.config来完成的.

下面我给出一种单个应用独立解决的办法, 方法很简单就是修改这个只读属性.

先通用你自己的工具查看一下代码实现, 我这里是用Reshaper通过从微软那里下载下来的.

/// <summary>
/// Gets the default maximum timeout interval for new transactions.
/// </summary>
/// 
/// <returns>
/// A <see cref="T:System.TimeSpan"/> value that specifies the maximum timeout interval that is allowed when creating new transactions.
/// </returns>
public static TimeSpan MaximumTimeout
{
  get
  {
    if (!TransactionManager._platformValidated)
      TransactionManager.ValidatePlatform();
    if (DiagnosticTrace.Verbose)
      MethodEnteredTraceRecord.Trace(SR.GetString("TraceSourceBase"), "TransactionManager.get_DefaultMaximumTimeout");
    if (!TransactionManager._cachedMaxTimeout)
    {
      lock (TransactionManager.ClassSyncObject)
      {
        if (!TransactionManager._cachedMaxTimeout)
        {
          TransactionManager._maximumTimeout = TransactionManager.MachineSettings.MaxTimeout;
          TransactionManager._cachedMaxTimeout = true;
        }
      }
    }
    if (DiagnosticTrace.Verbose)
      MethodExitedTraceRecord.Trace(SR.GetString("TraceSourceBase"), "TransactionManager.get_DefaultMaximumTimeout");
    return TransactionManager._maximumTimeout;
  }
}

看上去只要读取一些Config文件然后修改_maximumTimeout这个就可以了.实现代码如下:

    private static void ChangeTransactionManagerMaximumTimeout()
    {
        var customMaximumTimeout = TimeSpan.MaxValue;
        var maximumTimeout = TransactionManager.MaximumTimeout;

        FieldInfo fieldInfo = typeof(TransactionManager).GetFields(BindingFlags.NonPublic | BindingFlags.Static).Single(item => item.Name == "_maximumTimeout");
        fieldInfo.SetValue(null, customMaximumTimeout);
        maximumTimeout = TransactionManager.MaximumTimeout;
    }

这样在以后程序内部再次调用TransactionManager.MaximumTimeout就是修改过的timeout了.