TransactionScope 和数据库连接

发布于 2024-10-17 06:45:57 字数 368 浏览 4 评论 0原文

TransactionScope 是否适用于关闭的数据库连接?

using (var transaction = new TransactionScope(TransactionScopeOption.Required))
{
    // creates a new connection, does stuff, commit trans and close
    repos1.DoSomething(); 

    // creates a new connection, does stuff, commit trans and close
    repos2.DoSomething(); 

    transaction.Complete();
}

Do TransactionScope work with closed database connections?

using (var transaction = new TransactionScope(TransactionScopeOption.Required))
{
    // creates a new connection, does stuff, commit trans and close
    repos1.DoSomething(); 

    // creates a new connection, does stuff, commit trans and close
    repos2.DoSomething(); 

    transaction.Complete();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

┈┾☆殇 2024-10-24 06:45:57

是的,那应该可以正常工作。在内部,连接应保持打开状态,直到事务完成。请记住,如果使用多个连接,即使它们连接到同一数据库,也可能需要 DTC。

另外,你没有提到你正在使用哪个数据库,但 MySQL 实现中存在错误导致它无法工作。对于 MySQL,此问题在 MySQL 5.1.3 中已修复

Yes, that should work fine. Internally, the connections should be kept open until the transaction completes. Keep in mind that DTC may be required if multiple connections are used though, even if they are to the same database.

Also, you don't mention which database you are using, but there were bugs in the MySQL implementation that caused this not to work. For MySQL, this was fixed in MySQL 5.1.3.

假面具 2024-10-24 06:45:57

http://msdn.microsoft.com/en -us/library/system.data.sqlclient.sqlconnection.close.aspx

通过 System.Transactions 启动的事务通过 System.Transactions 基础结构进行控制,并且不受 SqlConnection.Close 的影响。

调用 Close 仅​​意味着您的代码已完成连接。如果 ADO.NET 基础结构仍然需要连接(以完成事务或连接池),则连接保持打开状态。

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx

Transactions started through System.Transactions are controlled through the System.Transactions infrastructure, and are not affected by SqlConnection.Close.

Calling Close just means that your code is done with the connection. If the ADO.NET infrastructure still wants the connection (to complete a transaction, or for connection pooling), the connection remains open.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文