TransactionScope 是否可以与预先存在的连接一起使用?
我有这样的代码:
try
{
using (TransactionScope scope = new TransactionScope())
{
some_db_function();
for (i = 0; i < 10; i++)
{
some_other_db_function();
}
scope.Complete();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " all done transactions will rollback");
}
在数据库函数内部会发生这样的事情:
private void some_db_functions()
{
using (TransactionScope scope = new TransactionScope())
{
//some processing on db
scope.Complete();
}
}
应该是如果数据库事务中存在任何问题,例如在函数中插入或更新时出错;迄今为止已完成的所有交易都将被回滚。但事实并非如此;尽管它抛出异常并且父函数中的scope.Complete()永远不会被触发,但仍然没有任何回滚。
问题出在哪里?
I have a code like this:
try
{
using (TransactionScope scope = new TransactionScope())
{
some_db_function();
for (i = 0; i < 10; i++)
{
some_other_db_function();
}
scope.Complete();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " all done transactions will rollback");
}
and inside the db functions something like this happens:
private void some_db_functions()
{
using (TransactionScope scope = new TransactionScope())
{
//some processing on db
scope.Complete();
}
}
It is supposed to be that if there was any problem in the database transactions, like an error inserting or updating in the functions; all the transactions that had been done so far get rolled back. But it does not work like that; and although it throws an exception and the scope.Complete()
in the parent function never gets triggered, still nothing get rolled back.
Where is the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果打开的连接已经存在,它将不会自动加入环境事务。您必须明确设置它。
参考。
这将征用现有连接:
If the open connection already exists it will not automatically enlist in an ambient transaction. You would have to set it explicitly.
Ref.
This will enlist an existing connection:
IIRC,自动登记到环境事务中发生在连接创建/打开时;如果您在事务范围内创建连接,那么一切都应该很好。然而:
如果该连接存在于事务之外,则它将不会登记。
最佳实践是仅围绕工作单元创建/打开连接,而不是永远创建/打开连接(并且:让连接池完成其工作)。如果你遵循这种做法,它应该会很好地工作。所以:
这不会起作用:
这应该起作用:
IIRC, automatic enlisting into ambient transactions happens at connection creation/opening time; if you create the connection inside the scope of the transaction, all should be good. However:
if the connection exists outside of the transaction, it won't enlist.
Best practice is to create/open a connection only around a unit of work, not forever (and: let connection pooling do its job). If you follow that practice, it should work fine. So:
This won't work:
where-as this should work: