【问题标题】:Question About TransactionScope in .NET关于 .NET 中的 TransactionScope 的问题
【发布时间】:2010-05-30 13:53:54
【问题描述】:
using (TransactionScope scope = new TransactionScope())
{
    int updatedRows1 = custPh.Update(cust.CustomerID, tempPh1, 0);
    int updatedRows2 = custPh.Update(cust.CustomerID, tempPh2, 1);
    int updatedRows3 = cust.Update();

    if (updatedRows1 > 0 && updatedRows2 > 0 && updatedRows3 > 0)
    {
        scope.Complete();
    }
}

上面的 TransactionScope 代码结构是否正确?这是我第一次使用它,所以我尽量让它变得简单。

【问题讨论】:

  • 你用得很好。您可能需要确保根据您的要求加入/不加入环境事务。您可以使用 TransactionOptions 参数设置它们。 simpleverse.wordpress.com/2008/08/05/…
  • @Mike。您应该创建一个答案,因为它是正确的。
  • 其实我认为迈克的那篇文章可能已经过时了。 TransactionScope 不再只是 DTC 的包装器,这使得它更有用:stackoverflow.com/questions/1155941/…
  • 为了扩展 Mike 的评论,TransactionScope 的默认 IsolationLevel 是 Serializable(我曾经认为它是 ReadCommitted 并且对正在发生的数据库死锁感到非常惊讶)。 IsolationLevel 可以通过 TransactionOptions 结构参数设置到 TransactionScope 构造函数。 Mike 指的是 TransactionScopeOption 枚举参数。

标签: c# .net sql-server transactions transactionscope


【解决方案1】:

锁好,

但你所做的设计很糟糕。 如果不是每个表都有更新的行,那么您基本上是在进行回滚。 您永远不会知道您的交易是完成还是失败。这可能会使解决错误变得很痛苦。

如果出现问题,我宁愿抛出异常。这也会导致回滚。因为 scope.Complete() 永远不会到达。

using (TransactionScope scope = new TransactionScope())
{
    int updatedRows1 = custPh.Update(cust.CustomerID, tempPh1, 0);
    int updatedRows2 = custPh.Update(cust.CustomerID, tempPh2, 1);
    int updatedRows3 = cust.Update();

    if (updatedRows1 == 0 || updatedRows2 == 0 || updatedRows3 == 0)
        throw new Exception("Not all rows could be updated");

    scope.Complete();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多