Как знать, ли код в TransactionScope?

Надеюсь, еще не поздно. У меня были подобные проблемы в VS 2013. Я обнаружил, что закрепленные вкладки были потеряны после перезапуска и последующего запуска Solution, когда у нас установлен плагин Productivity Power Tools установлен .

Я удалил его, и теперь закрепленные вкладки с тех пор не потеряны.

28
задан abatishchev 3 April 2016 в 05:54
поделиться

2 ответа

Вот более надежный способ (как я уже сказал, Transaction.Current можно установить вручную, и это не всегда означает, что мы действительно находимся в TransactionScope). Также возможно получить эту информацию с помощью отражения, но излучение IL работает в 100 раз быстрее, чем отражение.

private Func<TransactionScope> _getCurrentScopeDelegate;

bool IsInsideTransactionScope
{
  get
  {
    if (_getCurrentScopeDelegate == null)
    {
      _getCurrentScopeDelegate = CreateGetCurrentScopeDelegate();
    }

    TransactionScope ts = _getCurrentScopeDelegate();
    return ts != null;
  }
}

private Func<TransactionScope> CreateGetCurrentScopeDelegate()
{
  DynamicMethod getCurrentScopeDM = new DynamicMethod(
    "GetCurrentScope",
    typeof(TransactionScope),
    null,
    this.GetType(),
    true);

  Type t = typeof(Transaction).Assembly.GetType("System.Transactions.ContextData");
  MethodInfo getCurrentContextDataMI = t.GetProperty(
    "CurrentData", 
    BindingFlags.NonPublic | BindingFlags.Static)
    .GetGetMethod(true);

  FieldInfo currentScopeFI = t.GetField("CurrentScope", BindingFlags.NonPublic | BindingFlags.Instance);

  ILGenerator gen = getCurrentScopeDM.GetILGenerator();
  gen.Emit(OpCodes.Call, getCurrentContextDataMI);
  gen.Emit(OpCodes.Ldfld, currentScopeFI);
  gen.Emit(OpCodes.Ret);

  return (Func<TransactionScope>)getCurrentScopeDM.CreateDelegate(typeof(Func<TransactionScope>));
}

[Test]
public void IsInsideTransactionScopeTest()
{
  Assert.IsFalse(IsInsideTransactionScope);
  using (new TransactionScope())
  {
    Assert.IsTrue(IsInsideTransactionScope);
  }
  Assert.IsFalse(IsInsideTransactionScope);
}
6
ответ дан 28 November 2019 в 03:18
поделиться

Transaction.Current должен быть надежным; Я только что проверил, он отлично работает и с подавленными транзакциями:

Console.WriteLine(Transaction.Current != null); // false
using (TransactionScope tran = new TransactionScope())
{
    Console.WriteLine(Transaction.Current != null); // true
    using (TransactionScope tran2 = new TransactionScope(
          TransactionScopeOption.Suppress))
    {
        Console.WriteLine(Transaction.Current != null); // false
    }
    Console.WriteLine(Transaction.Current != null); // true
}
Console.WriteLine(Transaction.Current != null); // false
42
ответ дан 28 November 2019 в 03:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: