【C#】TransactionScopeのタイムアウトを10分以上にする

はじめに

TransactionScopeのタイムアウトはデフォルト1分で、最大10分まで伸ばす事ができます。
10分以上に設定したい場合、machine.configを使う方法がよく出てくるのですが、
machine.configを使わず10分超のタイムアウトを設定できる方法を記載します。

ソースコード

リフレクションを使用する事で、任意のタイムアウトの時間を設定できるようになります。

public static class TransactionScopeHelper
{
    public static TransactionScope Create(TimeSpan timeout)
    {
        typeof(TransactionManager).GetField("s_cachedMaxTimeout", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, true);
        typeof(TransactionManager).GetField("s_maximumTimeout", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, timeout);
        return new TransactionScope(TransactionScopeOption.Required, timeout, TransactionScopeAsyncFlowOption.Enabled);
    }
}

使い方

using (var scope = TransactionScopeHelper.Create(new TimeSpan(0, 30, 0)))
{
    scope.Complete();
}

未分類C#

Posted by ababa