在SQL中,默认的最大事务超时时间是多少?

13

如果 machine.config 中没有 "system.transactions" 元素,那么 maxTimeout 的默认值是多少(见示例)?

<system.transactions>
   <machineSettings maxTimeout="??:??:??" />
</system.transactions>

我之所以提出这个问题是因为代码崩溃了,原因是发生了以下异常,并且似乎与事务超时有关,在SaveChanges方法执行期间程序崩溃了,我收到的异常信息如下:

The transaction associated with the current connection has completed
but has not been disposed. The transaction must be disposed before
the connection can be used to execute SQL statements.

这是导致程序崩溃的代码片段:

using (TransactionScope transaction = TransactionHelper.CreateTransactionScope())
{
    using (EFContext efDBContext = new EFContext())
    {
        try
        {
            efDBContext.Connection.Open();  

            foreach (MyEntity currentEntity in myEntities)
            {
                //Insertion
            }

            transaction.Complete();
        }
        catch (Exception ex)
        {
            //Inspect current entity
            //Get Total Time of the run
            //Number of entities processed
        }
        finally
        {
            if (esfDBContext.Connection.State == ConnectionState.Open)
                esfDBContext.Connection.Close();
        }
    }
}

这是我创建TransactionScope的方法:

public static TransactionScope CreateTransactionScope(TransactionScopeOption option = TransactionScopeOption.Required, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
{
    var transactionOptions = new TransactionOptions()
    {
        Timeout = TimeSpan.MaxValue,
        IsolationLevel = isolationLevel
    };

    return new TransactionScope(option, transactionOptions);
}

4
几乎没有人知道这件事,但你需要非常小心。你的 machine.config 总是具有优先权:http://blog.muonlab.com/2011/08/03/net-4-transactionscope-timeout-is-ignored-if-greater-than-machine-config-maxtimeout-setting/ - "...如果你提供的超时时间大于 machine.config 值,[运行时] 会忽略它并使用 machine.config 的值。悄然无声,没有任何抱怨或警告。" - rohancragg
这里有一个非常好的答案:https://dev59.com/AXM_5IYBdhLWcg3wgzdl#1367630 - Piane_Ramso
在创建具有最大超时时间的TransactionScope时,请考虑使用TransactionManager.MaximumTimeout而不是TimeSpan.MaxValue(请参见https://stackoverflow.com/a/21935333/7665486)。 - Oliver Schimmer
2个回答

19

1
http://msdn.microsoft.com/en-us/library/system.transactions.configuration.machinesettingssection.maxtimeout.aspx - rohancragg

9

1
很抱歉,我没有听清您的评论。事务持续时间在服务器上配置了几个地方,“machine.config”是最重要的,“app.config”和代码级别也可以配置。如果使用代码,则会忽略“app.config”,但是如果超过了似乎会使用TransactionManager.DefaultTimeout,默认为1分钟,我不确定这一点,但我正在尝试确认。 - Bongo Sharp
通常在SQL中有命令超时和.NET中的页面超时。实际抛出的异常是什么? - iain
当前连接关联的事务已完成但尚未处理。在使用连接执行SQL语句之前,必须处理该事务。 - Bongo Sharp
听起来你没有清理对象和关闭连接。你能把代码粘贴在问题里,我可以调试一下吗? - iain
请看上面的代码,我将所有的调用都包含在using语句中,这不应该有问题。 - Bongo Sharp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,