是否需要显式事务回滚? [英] Is Explicit Transaction Rollback Necessary?

查看:80
本文介绍了是否需要显式事务回滚?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多示例都主张对数据库事务进行显式回滚,具体做法如下:

Many examples out there advocate explicit rollback of database transactions, along the lines of:

using (var transaction = ...)
{
    try
    {
        // do some reading and/or writing here

        transaction.Commit();
    }
    catch (SqlException ex)
    {
        // explicit rollback
        transaction.Rollback();
    }
}

但是,我倾向于这样做:

However, I tend to do this:

using (var transaction = ...)
{
    // do some reading and/or writing here

    transaction.Commit();
}

当发生异常时,我只是依靠未提交事务的隐式回滚.

When an exception occurs, I'm just relying on the implicit rolling back of transactions that aren't committed.

依赖于此隐式行为是否有任何问题?有人有令人信服的理由为什么我不应该这样做吗?

Is there any problem relying on this implicit behavior? Does anyone have a convincing reason why I shouldn't be doing it this way?

推荐答案

否,不是特别需要,但是我可以想到两个可能是个好主意的原因:

No, its not specifically needed, however I can think of 2 reasons why it might be a good idea:

  • 清晰度

有些人可能会争辩说,使用 transaction.Rollback()可以使交易在什么情况下都不会落实.

Some might argue that using transaction.Rollback() makes it clearer under what circumstances the transaction will not be committed.

  • 释放锁

在处理事务时,重要的是要意识到只有在回滚或提交事务时才会释放某些锁.如果使用的是 using 语句,则在处理该事务时将回滚该事务,但是,由于某种原因,您需要在 using 内进行一些错误处理.块,在执行复杂/耗时的错误处理之前回滚事务(删除锁)可能是有利的.

When dealing with transactions it is important to realise the certain locks will only be released when the transaction is rolled back or committed. If you are using the using statement then the transaction will be rolled back when the transaction is disposed of, however if for some reason you need to do some error handling inside the using block, it may be advantageous to rollback the transaction (removing the locks) before performing complex / time consuming error handling.

这篇关于是否需要显式事务回滚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆