我正在使用:
public class TransactionUtils
{
public static TransactionScope CreateTransactionScope()
{
var TransactionOptions = new TransactionOptions();
TransactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
TransactionOptions.Timeout = TimeSpan.MaxValue;
return new TransactionScope(TransactionScopeOption.Required, TransactionOptions);
}
}来创建我的所有交易。我面临的问题是,当我嵌套2个TransactionUtils.CreateTransactionScope()时,我得到一个错误:Time-out interval must be less than 2^32-2. Parameter name: dueTm。我假设这是因为它试图将子事务附加到父事务,并且组合的超时过大。
有没有办法判断新创建的事务是否是嵌套事务,这样我就可以避免设置超时?
另一种选择是向CreateTransactionScope()传递一个参数,这样我就可以告诉它它是嵌套的,并且不设置超时,但我更愿意找到一种自动处理它的方法。
发布于 2013-03-23 04:45:31
有一个非常简单的答案:
System.Transactions.Transaction.Current != null从Framework2.0开始就是这样。
我不确定为什么另一个答案会如此深入地创建链接到非公共字段的IL。
发布于 2012-12-12 18:15:39
是的,这是可能的。我有以下代码。我不是自己做的,但是忘了在哪里买的。称赞原作者,但我记得我只是发现它在谷歌上搜索。我在.net 4.0中使用它,不知道它与其他版本的兼容性如何(它取决于特定程序集中的特定类)。
使用下面的代码,您可以检查代码中的某个点是否在事务作用域内执行。
class TransactionScopeDetector {
private Func<TransactionScope> _getCurrentScopeDelegate;
public 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>));
}
}https://stackoverflow.com/questions/13837338
复制相似问题