meh*_*ish 0 c# entity-framework transactions transactionscope
我无法修改客户端上的 machine.config
嵌套事务中有没有其他方法可以让它们持续超过 10 分钟?隔离级别或任何其他选项是否有助于解决超时问题。我的内部事务DoWork()很好,我认为是外部事务超时了。
private void DoAllWork()
{
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TransactionManager.MaximumTimeout))
{
DoWork();
scope.Complete();
}
}
private void DoWork()
{
Foreach(Some long running loop)
{
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TransactionManager.MaximumTimeout))
{
// Entity Framework queries / modification / Save Changes
scope.Complete();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到过同样的问题 。您需要在 machine.config 中更改它。这些设置不起作用。但是更改 machine.config 并不好,所以我像这样解决了它。我所做的是在运行时获取事务管理器对象并更新其值,它对我有用。
public TransactionScope CreateTransactionScope(TimeSpan timeout)
{
SetTransactionManagerField("_cachedMaxTimeout", true);
SetTransactionManagerField("_maximumTimeout", timeout);
var transactionScopeOptions = new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadUncommitted,
Timeout = timeout
};
return new TransactionScope(TransactionScopeOption.RequiresNew, transactionScopeOptions);
}
private void SetTransactionManagerField(string fieldName, object value)
{
typeof(TransactionManager).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, value);
}
Run Code Online (Sandbox Code Playgroud)
我这样使用它
using (var scope = CreateTransactionScope(TimeSpan.FromMinutes(50)))
{
// do something
scope.Complete();
}
catch (Exception e)
{
new Logger().LogException(e);
}
Run Code Online (Sandbox Code Playgroud)