Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is more reliable way (as I said, Transaction.Current can be set manually and it doesn't always mean we are really in TransactionScope). It's also possible to get this information with reflection, but emiting IL works 100 times faster than reflection.</p> <pre><code>private Func&lt;TransactionScope&gt; _getCurrentScopeDelegate; bool IsInsideTransactionScope { get { if (_getCurrentScopeDelegate == null) { _getCurrentScopeDelegate = CreateGetCurrentScopeDelegate(); } TransactionScope ts = _getCurrentScopeDelegate(); return ts != null; } } private Func&lt;TransactionScope&gt; 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&lt;TransactionScope&gt;)getCurrentScopeDM.CreateDelegate(typeof(Func&lt;TransactionScope&gt;)); } [Test] public void IsInsideTransactionScopeTest() { Assert.IsFalse(IsInsideTransactionScope); using (new TransactionScope()) { Assert.IsTrue(IsInsideTransactionScope); } Assert.IsFalse(IsInsideTransactionScope); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload