TransactionScope 超时过早发生?
我正在使用 TransactionScope
进行一些批量插入和更新。问题是,即使我将 TransactionScope
的超时设置为一小时,我也会在 30 分钟长的操作中遇到超时异常。
此外,在异常之后,它会插入看似随机数量的批次记录。例如,最后一个操作有 12440 条插入,超时后有 7673 条记录插入到表中。
SqlConnection
和 SqlCommand
的超时均设置为 int.MaxValue
。
我做错了什么?
这是我的代码:
using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromHours(1)))
{
try
{
using (db = new DB())
{
//operations here
}
}
catch (Exception ex)
{
throw new Exception("DB Error:\r\n\r\n" + ex.Message);
}
transaction.Complete();
} // <--- Exception here: Transaction aborted (Inner exception: Timeout)
I'm using TransactionScope
to do some batch insert and updates. Problem is, I'm getting timeout exceptions on a 30 min long operation even when I set the timeout of the TransactionScope
to one hour.
Also after the exception it inserts seemingly random amount of the records of the batch. For example the last operation had 12440 inserts and after the timeout there were 7673 records inserted to the table.
The timeout of the SqlConnection
and SqlCommand
are both set to int.MaxValue
.
What am I doing wrong?
Here's my code:
using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromHours(1)))
{
try
{
using (db = new DB())
{
//operations here
}
}
catch (Exception ex)
{
throw new Exception("DB Error:\r\n\r\n" + ex.Message);
}
transaction.Complete();
} // <--- Exception here: Transaction aborted (Inner exception: Timeout)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的交易是否在 10 分钟后失败?如果是这样,您可能遇到了事务管理器最大超时< /a> 这是在 machine.config 中设置的。如果我没记错的话,如果您尝试设置大于最大值的超时,那么您的设置将被忽略。尝试增加 machine.config 中的值,看看这是否对您的问题有帮助。
就随机提交而言,您是否在连接字符串上设置了
Transaction Binding=Explicit Unbind
?默认值为事务绑定=隐式解除绑定
。来自 MSDN:基本上,当事务超时时,截至该点的所有插入都将回滚,但使用同一连接完成的任何其他插入都将以自动提交模式完成,其中每个插入语句都将立即提交。这听起来确实与您所看到的场景类似(但如果不看到完整的代码/重现就很难知道)。
Is your transaction failing after 10 minutes? If so, you are probably hitting the Transaction Manager Maximum Timeout which is set in the machine.config. If I recall correctly, if you try to set a timeout greater than the maximum value then your setting will be ignored. Try upping the value in machine.config and see if that helps your issue.
In terms of random commits do you set
Transaction Binding=Explicit Unbind
on your connection string? The default value isTransaction Binding=Implicit Unbind
. From MSDN:Basically, when the transaction times out all inserts up to that point will be rolled back but any additional inserts done using the same connection will be done in autocommit mode where every insert statement will be immediately committed. That does sound similar to the scenario you are seeing (but it's hard to know without seeing the full code/repro).
我想看看您是否可以利用 SqlBulkCopy 类。它应该更快,并且可能消除长时间超时的需要。
I would see if you can utilise the SqlBulkCopy Class. It should be much faster, and might eliminate the need for a long timeout.